如何知道 JavaScript 中哪个元素调用了函数?
我正在做这个页面,其中有很多图像链接,当鼠标悬停在它们上方时,这些链接会发生变化。我在这里有一个更改图像的函数:
function hoverImg(element) {
if (element.src.indexOf("_hover.png") == -1) {
element.src = element.src.replace(".png","_hover.png");
} else {
element.src = element.src.replace("_hover.png",".png");
}
}
但是,我必须为每个元素的每个 onmouseover 和 onmouseout 事件提供“this”作为该函数的参数。有没有办法只知道什么元素称为函数?函数复制不是一种选择,因为正如我所说,每页可能有数百个这样的小图像,并且无论如何这些页面最终都会从数据库数据生成。每次添加“这个”似乎非常多余......
I'm doing this page with a lot of image links that change when the mouse hovers above them. I have a function for changing the image here:
function hoverImg(element) {
if (element.src.indexOf("_hover.png") == -1) {
element.src = element.src.replace(".png","_hover.png");
} else {
element.src = element.src.replace("_hover.png",".png");
}
}
However, I have to give "this" as a parameter for the function on each onmouseover and onmouseout event for each element. Is there a way to just know what element called a function? Function copying isn't an option because, as I said, there'll possibly be a good hundred of these small images per page and the pages will be eventually generated from database data anyway. Adding "this" each time seems highly redundant...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
两个选项(以 onclick 为例):
来自 html:
onclick="javascript:hoverImg(this)"
或来自代码:
x.onclick = hooverImg
(this< /code> 现在在回调中设置好,因为它稍后会“调用” x 中的对象)。
还有一些“行为”JavaScript 库(甚至是 jQuery —— 甚至可能是 jQuery.live )可能会帮助你得到你想要的。
Two options (onclick as example):
from html:
onclick="javascript:hoverImg(this)"
or from code:
x.onclick = hoverImg
(this
set okay now in callback because it is "invoked upon" the object in x later).There are also some "behavior" JavaScript libraries (or even jQuery -- perhaps jQuery.live even) which may help you get what you want.
在您的函数中尝试
window.event.srcElement
。这假设它是直接从事件处理程序调用的。Try
window.event.srcElement
in your function. This assumes it's invoked directly from an event handler.