简体   繁体   English

循环内的Javascript函数

[英]Javascript function inside loop

Any one have any idea why this doesn't work as expected? 任何人都知道为什么这不能按预期进行吗? Just fires alerts on page load. 只是在页面加载时触发警报。

var div = document.querySelectorAll('.div'); // NodeList of all instances of '.div'

var eventFunction = function() {
  alert('ggdf');
};


for(var i = 0; i < div.length; i++) { // Begin '.div' NodeList loop

  div[i].addEventListener('click', eventFunction(), false); // Click function on all instances of '.div'

} // End '.div' NodeList loop

Your executing the function when passing it to the eventListener function, instead use: 将函数传递给eventListener函数时,应执行该函数,而应使用:

for(var i = 0; i < div.length; i++) {  
  div[i].addEventListener('click', eventFunction, false); //notice no ()
}

Functions can be passed as arguments the same way as other variables, but when you pass them with () after them your invoking the function and the object/value returned by the function is passed as the argument. 可以将函数作为参数传递,方法与其他变量相同,但是在函数之后用()传递时,调用函数和函数返回的对象/值作为参数传递。

Also unless you have added a class div to all your divs I think you want to use a tag selector: 另外,除非您向所有div中添加了一个div类,否则我认为您想使用标签选择器:

var div = document.querySelectorAll('div'); 

JS Fiddle: http://jsfiddle.net/rG3AC/1/ JS小提琴: http //jsfiddle.net/rG3AC/1/

您需要绑定该函数,以便它不会立即触发。

div[i].addEventListener('click', eventFunction.bind(), false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM