addEventListener在点击时不触发功能 [英] addEventListener not triggering function on click
本文介绍了addEventListener在点击时不触发功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个问题的解决方案可能很简单,但我需要一些帮助。
the solution to this problem is probably pretty simple, but I need some help.
var x;
for(x in document.getElementsByTagName("img"))
x.addEventListener('click',openPage, false);
function openPage() {
alert("clicked");
}
当我点击<$ c $时,我没有收到提醒c>< img src =something/> 标签。谁知道为什么?另外,我的循环是否必要?
I'm not getting an alert when I click on an <img src="something" />
tag. Anyone know why? Also, is my loop necessary?
推荐答案
此代码产生错误 - 在for..in语句中,'x'是对象的键(在本例中为 document.getElementsByTagName
调用)。你想要的是:
This code produces an error - in a for..in statement, 'x' is the key of your object (in this case, your document.getElementsByTagName
call). What you want is:
var x,
imgs = document.getElementsByTagName("img");
for(x in imgs) {
if (imgs[x] instanceof Element) {
imgs[x].addEventListener('click',openPage, false);
}
}
function openPage() {
alert("clicked");
}
我建议使用Javascript框架(如 jQuery ),它可以帮助您简化代码:
Might I suggest using a Javascript framework (like jQuery), which can help simplify your code as such:
$('img').each(function() {
$(this).click(function() {
alert('Clicked!');
// Now that we're in the callback context, $(this) will be the current
// target - the specific image that was clicked.
// i.e. $(this).fadeOut() would slowly fade out the clicked image.
});
});
这篇关于addEventListener在点击时不触发功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文