addEventListener not triggering function on click

时光怂恿深爱的人放手 提交于 2019-12-31 04:44:06

问题


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. Anyone know why? Also, is my loop necessary?


回答1:


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

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


来源:https://stackoverflow.com/questions/9610775/addeventlistener-not-triggering-function-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!