开发者

Value gets passed to function without me clicking the button

When I try to pass a value when a button is clicked the value gets passed anyway (even without me clicking the button). This is not supposed to happen because I want to hide an image only when the button is clicked Why is this happening?

for ( i = 0; i < divs.length;i++){  
    knopdiv[i] = document.createElement('div');  
    divs[i].appendChild(knopdiv[i]);  
    knopdiv[i].innerHTML = '<button id="knop' +i+'">Afbeelding verbergen</button>';  
    knopdiv[i].onclick = hideMe(i开发者_开发问答, afb[i]);


function hideMe(nummer, afb){
console.log (nummer);
}

output without clicking:

0
1
2
3
4
5
6
7
8

Why isn't console just passing the number of the clicked button?


knopdiv[i].onclick = hideMe(i, afb[i]); when this statement is executed, hideMe() is fired!
change it to :

knopdiv[i].onclick = (function(i, element){
    return function(){
        hideMe(i, element);
    };
})(i, afb[i]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜