coffeecup
11-10-2012, 10:21 PM
Hey! very basic question in regards of divs & onclick function:
whenever the function init(Amount) is triggered, it should create divs with an onclick function.
now the onclick function for every div is already triggered the moment init(Amount) is performed (so the alert would pop up once for every div).
why is that? :/
issued part of the code:
function init(Amount)
{
var gameDeck = [
"c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8"
]
gameDeck.shuffle();
var newdiv;
for(var i=0;i<Amount*2;i++) {
newdiv=document.createElement("div");
newdiv.setAttribute("style","float: left; margin: 10px;");
newdiv.style.width = '65px';
newdiv.style.height = '65px';
newdiv.style.border = '1px solid red';
newdiv.id = gameDeck[i];
newdiv.onclick = divClick();
document.getElementById('playfield').appendChild(newdiv);
}
}
function divClick() {
alert("Clicked");
}
if I replace
newdiv.onclick = divClick();
with
newdiv.onclick = function() {alert("Clicked");};
it actually works... why? :confused:
whenever the function init(Amount) is triggered, it should create divs with an onclick function.
now the onclick function for every div is already triggered the moment init(Amount) is performed (so the alert would pop up once for every div).
why is that? :/
issued part of the code:
function init(Amount)
{
var gameDeck = [
"c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8"
]
gameDeck.shuffle();
var newdiv;
for(var i=0;i<Amount*2;i++) {
newdiv=document.createElement("div");
newdiv.setAttribute("style","float: left; margin: 10px;");
newdiv.style.width = '65px';
newdiv.style.height = '65px';
newdiv.style.border = '1px solid red';
newdiv.id = gameDeck[i];
newdiv.onclick = divClick();
document.getElementById('playfield').appendChild(newdiv);
}
}
function divClick() {
alert("Clicked");
}
if I replace
newdiv.onclick = divClick();
with
newdiv.onclick = function() {alert("Clicked");};
it actually works... why? :confused: