如何知道 JavaScript 中哪个元素调用了函数?

发布于 2024-10-07 21:14:47 字数 508 浏览 0 评论 0原文

我正在做这个页面,其中有很多图像链接,当鼠标悬停在它们上方时,这些链接会发生变化。我在这里有一个更改图像的函数:

    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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夜夜流光相皎洁 2024-10-14 21:14:47

两个选项(以 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.

梦在夏天 2024-10-14 21:14:47

在您的函数中尝试 window.event.srcElement 。这假设它是直接从事件处理程序调用的。

Try window.event.srcElement in your function. This assumes it's invoked directly from an event handler.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文