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.
精彩评论