I have a problem with addEvent(or something else I don’t know). This is my code.
HTML :
<div style="background-color:red;height:30px;width:30px;" ></div>
<div style="background-color:yellow;height:30px;width:30px;" ></div>
JS :
function addEvent(elm,ev,fun)//Cross-browser addEvent
{
if(elm.addEventListener)elm.addEventListener(ev,fun,false);
else if(elm.attachEvent)
{
var r=elm.attachEvent("on"+ev,fun);
return r;
}
}
function myFun(x)
{
alert(x.style.backgroundColor);
}
var allDiv=document.getElementsByTagName("div");
myFun(allDiv[0]);//Here it works
for(var i=0;i<allDiv.length;i++) {
//But not here when you click the div
addEvent(allDiv[i],
"click",function(){
myFun(allDiv[i])
});
}
I want that the alert works but without using IDs and without puting an inline onclick. Is it possible ?
You’ve fall into a common trap when using closures in JavaScript. I is closed over but changes on all click functions are calling myFunc with
allDiv[allDiv.length -1]you can use a self executing function to get around thisthis no longer closes over i (i is never referenced in the function assigned to the click event).
in this particualr case however you can simply pass this. An event handler is called in the context of the element firing the event so you can do
or even shorter using jQuery