简体   繁体   English

为什么我的事件监听器不起作用?

[英]Why is my event listener not working?

I've been searching all over the place and even if I have found the answer, it has not been delivered in terms I can understand. 我一直在到处搜寻,即使找到答案,也无法按照我能理解的术语提供。 I'm playing around with this code on jsfiddle, trying to understand why this click handler is not working. 我在jsfiddle上玩这些代码,试图了解为什么此点击处理程序不起作用。 I apologize if this is a useless post, just trying to make sense of it all. 如果这是一个无用的帖子,我深表歉意,只是想使这一切有意义。 If anyone knows any good tutorials on how javascript code is rendered and how functions pass objects etc.. please, do link me! 如果有人知道有关如何呈现javascript代码以及函数如何传递对象等的任何很好的教程,请联系我! I've read the basics of how to write functions etc.. but understanding whats going on when the code is parsed, to me, is quite a different thing. 我已经阅读了有关如何编写函数等的基础知识。但是,对我而言,了解在解析代码时发生的情况是完全不同的。

Here is the code I'm trying to get to work: 这是我要开始工作的代码:

http://jsfiddle.net/UumUP/3144/ http://jsfiddle.net/UumUP/3144/

// Function to change the content of t2  
function modifyText(evt) {  
  var thing = evt.target;
  thing.firstChild.nodeValue = "four";      
}  

// add event listener to t  
var el = document.getElementsByTagName("td");  

for(i = 0; i < el.length; i++) {
  el[i].addEventListener("click", modifyText(evt), false);   
}

You are calling the function and passing the result of that call, rather than passing a reference of the function, do this instead: 您正在调用该函数并传递该调用的结果,而不是传递该函数的引用,而是这样做:

el[i].addEventListener("click", modifyText, false);

http://jsfiddle.net/UumUP/3145/ http://jsfiddle.net/UumUP/3145/

el[i].addEventListener("click", modifyText(evt), false); 

supposed to be 应该是

el[i].addEventListener("click", modifyText, false); 

Check Fiddle 检查小提琴

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

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