Where this
does not refer to the element which may refer to the window
object instead pass the x
as argument and css()
is a jQuery method so either you need to wrap it using jQuery
or update style
property using JavaScript. Although attach click event by setting onClick
property.
var c = $("#container")[0];
for(var i=0; i<6;i++){
var x = document.createElement("div");
x.className = "sqare";
x.onClick = changecolor(p);
c.appendChild(x);
}
function changecolor(p){
return function() {
p.style.backgroundColor = "yellow";
}
}
The closure can be avoided here since this
context can be accessed within the handler.
var c = $("#container")[0];
for(var i=0; i<6;i++){
var x = document.createElement("div");
x.className = "sqare";
x.addEvenetListener('click', changecolor);
c.appendChild(x);
}
function changecolor(){
this.style.backgroundColor = "yellow";
}
Refer :
addEventListener vs onclick