【问题标题】:forEach function in JavaScript used for Button用于 Button 的 JavaScript 中的 forEach 函数
【发布时间】:2021-02-21 18:01:47
【问题描述】:

JS新手,有人能指出我在下面犯了什么错误吗?按钮不起作用。

<!DOCTYPE html>
<html>
<body>

<button onclick ="insertFunction()"> click me! </button>
<div id ="containerDiv">
</div>
<script>
 var textArray = [
 {name: "Harry"}, {place: "London"} ]
 
 function insertFunction() {
 textArray.forEach(function(value,index){
 var insertText = '<p>Hello' +value.name+'</p>';
 document.getElementBydID("containerDiv").innerHTML+=insertText;
 });
 }
 </script>
 </body>
 </html>

【问题讨论】:

  • 你有一个错字getElementBydID应该是getElementById
  • “不工作”不是诊断性的。请始终提供详细信息。

标签: javascript html button bootstrap-4


【解决方案1】:

您拼错了方法“getElementById()”。这是正确的实现

var textArray = [{ name: 'Harry' }, { place: 'London' }];
function insertFunction() {
  textArray.forEach(function (value, index) {
    var insertText = '<p>Hello' + value.name + '</p>';
    document.getElementById('containerDiv').innerHTML += insertText;
  });
}
<button onclick ="insertFunction()"> click me! </button>
<div id ="containerDiv">
</div>

【讨论】:

    【解决方案2】:
    <!DOCTYPE html>
    <html>
    <body>
    
    <button onclick ="insertFunction()"> click me! </button>
    <div id ="containerDiv">
    </div>
    <script>
     var textArray = [
     {name: "Harry",
     place: "London"},
     {name: "Andy",
     place: "USA"},
    
     ]
     
     function insertFunction() {
     textArray.forEach(function(value,index){
     var insertText = '<p>Hello ' +value.name+'</p>';
     document.getElementById("containerDiv").innerHTML+=insertText;
     });
     }
     </script>
     </body>
     </html>
    

    您在 getelementbyid 中有错字。如果需要,您的 JSON 也可以这样修改。

    【讨论】:

    • 如果是拼写错误,则有特定的关闭原因。
    【解决方案3】:

    getElementById 中有错字。因为我使用的是简单的代码编辑器,所以没有抓住这个! 谢谢大家!

    【讨论】:

      【解决方案4】:

      逻辑和循环存在一些问题,但首先,未触发点击事件的原因是语法错误

      document.getElementById("containerDiv").innerHTML+=insertText;
      

      您在 getElementByID 中有 D 大写字母,应将其更改为 getElementById,它将让您触发点击事件 但是,循环仍然有一个逻辑错误,我正在编写循环的更正版本,希望它可以帮助您考虑到循环背后没有故意的原因,如果是这样,您的解决方案在前几行结束

      <!DOCTYPE html>
      <html>
      <body>
      
      <button onclick ="insertFunction()"> click me! </button>
      <div id ="containerDiv">
      </div>
      <script>
       var textArray = [
       {name: "Harry"}, {name: "London"} ]
       
       function insertFunction() {
       var insertText = '';
       textArray.forEach(function(value,index){
       insertText = insertText  + '<p>Hello' +value.name+'</p> <br/>'; 
       });
      document.getElementById("containerDiv").innerHTML+=insertText;
       }
       </script>
       </body>
       </html>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-07
        • 1970-01-01
        • 2022-01-12
        • 1970-01-01
        相关资源
        最近更新 更多