Reputation: 1
I created div
elements by the loop and I want to change background-color
when I click the div
.
var c = $("#container")[0];
for(var i=0; i<6;i++){
var x = document.createElement("div");
x.className = "sqare";
x.click(changecolor(this));
c.appendChild(x);
}
function changecolor(p){
return function() {
p.css("background-color", "yellow");
}
}
I follow this Assign click handlers in for loop , but failed...
Upvotes: 0
Views: 99
Reputation: 573
You don't have to add event handler for each elements.
You can try to use only 1 click event.
Check my example below
SIMPLE HTML
<div id="container"></div>
JAVASCRIPT
var c = $("#container");
for(var i=0; i<6;i++){
$("<div class='sqare'>hello " + i + "</div>").appendTo(c);
}
$(".sqare").on("click",function(){
$(this).css("background-color","yellow");
});
And live example : https://jsfiddle.net/synz/amnapc70/
Upvotes: 0
Reputation: 115222
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";
}
Upvotes: 1