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

标签 javascript html

我想向表单添加一个事件监听器,以在段落中显示表单的字段,而不使用 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/

相关文章:

javascript - 新标签页被弹出窗口拦截器拦截

Python Beautiful Soup 找不到表

html - 如何在 content 和 content::before 上使用不透明度而不重叠

javascript - 防止 href 链接 jQuery

javascript - jQuery animate scrollTop 在 firefox 中不起作用

jquery - 输入点击不起作用

javascript - 如何绕过在 iPhone 中使用 html5 视频标签进行全屏播放?

javascript - 我可以关闭 HTML <canvas> 元素上的抗锯齿功能吗?

DataTables rowReordering (ASP.Net MVC) 期间的 JavaScript 运行时错误

javascript - 如何使用 VeeValidate (Vue.Js) 上的字典自定义 "required"错误消息