document.images 上的 JavaScript addEventListener

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8905183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:56:06  来源:igfitidea点击:

JavaScript addEventListener on document.images

javascriptevents

提问by Steffan Harris

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.

当我点击图片时,我试图通过 addEventListener 动态更改图片。我在documents.images数组中有图片。我已经编写了一个函数来切换图像。我遇到的问题是在单击图像时绑定它。

This is what I tried

这是我试过的

document.images[i]src.addEventListener("click", MakeMove, false);

回答by Adam Rackis

You 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

但是较旧的浏览器不支持这些 DOM Level 2 事件处理程序,因此,假设这些图像不必具有多个点击处理程序,请考虑这样做

document.images[i].onclick = MakeMove;

EDIT

编辑

To pass a parameter to MakeMove, you'd set onclickto an anonymous function that calls MakeMovewith whatever values you need:

要将参数传递给MakeMove,您需要设置onclick一个匿名函数,该函数MakeMove使用您需要的任何值进行调用:

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.

将是一个字符串,您显然无法向其中添加事件处理程序。

回答by adrian

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.com) to make sure to avoid this mistakes in the future!

需要直接在图像对象上添加事件监听器。使用 JSLint (www.jslint.com) 确保以后避免这种错误!

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.

注意:这仅适用于支持(除了 IE 之外的所有内容).addEventListner 的浏览器。最好使用库,这样您就不必担心这一点,但如果您需要, .attachEvent('onclick', MakeMove) 将处理 IE 和其他情况。