简体   繁体   中英

How to know which element called a function in Javascript?

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...

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM