gpt4 book ai didi

javascript - 函数结果显示在控制台但不显示在网页中

转载 作者:行者123 更新时间:2023-12-01 02:16:26 25 4
gpt4 key购买 nike

我想向表单添加一个事件监听器,以在段落中显示表单的字段,而不使用 jQuery。

文本应该显示在 demoJS 段落中,但事实并非如此。但是,当我使用 console.log 时,异常结果出现在控制台中。

这是我的代码:

function afficher_etudiant() {
document.getElementById("demoJS").innerHTML +=
document.getElementById("nom").value + "<br>" +
document.getElementById("prenom").value + "<br>" +
document.getElementById("num_etu").value + "<br>" +
document.getElementById("cursus").value + "<br>";
console.log(document.getElementById("demoJS").innerHTML);
}


var bouton = document.getElementById("formulaireJS");
bouton.addEventListener("onclick", afficher_etudiant);
bouton.addEventListener("onsubmit", afficher_etudiant);
bouton.addEventListener("submit", afficher_etudiant);
<p id="demoJS"> </p>
<form id="formulaireJS">
Nom:<br>
<input type="text" name="nom" id="nom" required>
<br> Prénom:
<br>
<input type="text" name="prenom" id="prenom" required>
<br> Numero étudiant:<br>
<input type="text" name="num_etu" id="num_etu" required>
<br>
<select name="cursus" id="cursus" form="formulaireJS">
<option value="math">math</option>
<option value="info">info</option>
<option value="cmi">CMI</option>
</select>
<br>
<br>
<br>
<br>
<input type="submit" value="Ajouter" class="boutonSoumission">
</form>

最佳答案

您可以通过两种方式修复代码:

  1. 直接调用函数并删除事件监听器

    <input type="button" onclick="afficher_etudiant()" value="Ajouter" class="boutonSoumission" >

    • 将类型更改为“按钮”而不是提交,因为这会刷新页面。
    • 直接使用onclick调用函数并删除脚本中事件监听器的代码
  2. 如果您想使用事件监听器:

        <input type="button"  value="Ajouter"  class="boutonSoumission" id="myButton" > // for the button code

    var bouton = document.getElementById("myButton") ; // In Script
    bouton.addEventListener("click",afficher_etudiant);
    • 添加类型为“按钮”并为按钮添加 ID

    • 只保留“click”事件监听器并删除其他事件监听器。还获取按钮的 ID,而不是表单的 ID。

关于javascript - 函数结果显示在控制台但不显示在网页中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49480885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com