简体   繁体   English

addEventListener不会在单击时触发功能

[英]addEventListener not triggering function on click

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");
}

I'm not getting an alert when I click on an <img src="something" /> tag. 单击<img src="something" />标记时没有收到警报。 Anyone know why? 有人知道为什么吗? Also, is my loop necessary? 另外,我的循环是否必要?

This code produces an error - in a for..in statement, 'x' is the key of your object (in this case, your document.getElementsByTagName call). 这段代码会产生错误-在for..in语句中,“ x”是对象的键(在这种情况下,就是您的document.getElementsByTagName调用)。 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");
}

Might I suggest using a Javascript framework (like jQuery ), which can help simplify your code as such: 我可能建议使用Javascript框架(如jQuery ),它可以帮助简化代码,例如:

$('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.
    });
});

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

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