问题
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