使用addEventListener调用forEach函数

时间:2018-11-22 09:39:09

标签: javascript

因此,我无法找到任何在线资源,这些事件显示通过单击基于forEach的事件监听器来触发事件监听器,我知道我在这里做错了,所以任何人都可以将我指向正确的方向。

这是我的代码

document.addEventListener('DOMContentLoaded',function(){

var numbers = [4, 9, 16, 25];

document.querySelector('button').addEventListener('click',numbers.forEach(myFunction))

function myFunction(item, index) {

  //create a new h1 element 
  var newH1 = document.createElement('h1'); 
  //
  
  //Insert content in the h1
  var innerH1 = document.createTextNode(item); 
  //
  
  //Add the text node to the newly created h1
  newH1.appendChild(innerH1);  
  //
  
  //Add the newly created element and its content into the DOM 
  document.body.insertBefore(newH1,document.body.secondChild);
  //
}

});
<button>Click me</button>

1 个答案:

答案 0 :(得分:2)

您可以尝试将numbers.forEach(myFunction);放到事件内部的函数中,如下所示:

document.addEventListener('DOMContentLoaded', function () {

    var numbers = [4, 9, 16, 25];

    document.querySelector('button').addEventListener('click', function () {
        numbers.forEach(myFunction);
    });

    function myFunction(item, index) {

        //create a new h1 element 
        var newH1 = document.createElement('h1');
        //

        //Insert content in the h1
        var innerH1 = document.createTextNode(item);
        //

        //Add the text node to the newly created h1
        newH1.appendChild(innerH1);
        //

        //Add the newly created element and its content into the DOM 
        document.body.insertBefore(newH1, document.body.secondChild);
        //

    }

});
<button>Click me</button>


语法:

selector.addEventListener(event, function () {
    // implement...
});