admin管理员组文章数量:1302267
I am trying to dynamically change a picture when I click on it, via the addEventListener. I have the pictures in the documents.images array. I already have a function written to switch the images. The problem I am having is binding this in the event that I click on an image.
This is what I tried
document.images[i]src.addEventListener("click", MakeMove, false);
I am trying to dynamically change a picture when I click on it, via the addEventListener. I have the pictures in the documents.images array. I already have a function written to switch the images. The problem I am having is binding this in the event that I click on an image.
This is what I tried
document.images[i]src.addEventListener("click", MakeMove, false);
Share
asked Jan 18, 2012 at 4:27
Steffan HarrisSteffan Harris
9,33630 gold badges76 silver badges101 bronze badges
1
- You're missing a "." after [i], that's probably the problem. – CBusBus Commented Jan 18, 2012 at 4:33
2 Answers
Reset to default 4You want to add the event to the actual image:
document.images[i].addEventListener("click", MakeMove, false);
but older browsers don't support these DOM Level 2 event handlers, so, assuming these images don't have to have multiple click handlers, consider doing
document.images[i].onclick = MakeMove;
EDIT
To pass a parameter to MakeMove
, you'd set onclick
to an anonymous function that calls MakeMove
with whatever values you need:
document.images[i].onclick = function() {
MakeMove(12);
}
From your original code:
document.images[i]src
isn't valid, and
document.images[i].src
would be a string, to which you obviously cannot add an event handler.
It looks like you have a syntax error.
Try:
document.images[i].addEventListener("click", MakeMove, false);
Need to add the event listener directly on the image object. Use JSLint (www.jslint.) to make sure to avoid this mistakes in the future!
Note: This will only work in browser that support (mostly everything but IE) .addEventListner. It's better probably to use a library so you don't have to worry about this, but if you need, .attachEvent('onclick', MakeMove) will handle IE and other cases.
本文标签: eventsJavaScript addEventListener on documentimagesStack Overflow
版权声明:本文标题:events - JavaScript addEventListener on document.images - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741712473a2393919.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论