2016-05-28 146 views
0

我有這個點擊事件附加到每個按鈕,當我點擊他們每個人,它是打印輸出意味着第三個按鈕。我不確定發生了什麼事。javascript onclick事件沒有正確觸發

<!DOCTYPE html> 
<html> 
<head> 
    <title>JS Bin</title> 
</head> 
<body> 
    <button>test1</button> 
    <button>test2</button> 
    <button>test3</button> 
</body> 
<script> 
    var nodes = document.getElementsByTagName('button'); 
    for (var i = 0; i < nodes.length; i++) { 
     nodes[i].addEventListener('click', function() { 
     console.log('You clicked element #' + i); 
    }); 
    } 
</script> 
</html> 

當我點擊任何按鈕,它是印刷

"You clicked element #3" 
+0

當'click'觸發時,它顯示'i'的最後一個值,它是3.您需要在這裏使用閉包。在這裏,你去http://stackoverflow.com/a/8802111/3639582 –

回答

3

簡單的解決這個:

<!DOCTYPE html> 
<html> 
<head> 
    <title>JS Bin</title> 
</head> 
<body> 
    <button>test1</button> 
    <button>test2</button> 
    <button>test3</button> 
</body> 
<script> 
    var nodes = document.getElementsByTagName('button'); 
    console.log(nodes); 
    for (var i = 0; i < nodes.length; i++) { 
     //converted click function into an IIFE so it executes then and 
     there only 
     nodes[i].addEventListener('click', (function(j) { 
     return function(){ 
      console.log('You clicked element #' + j);  
     } 

    })(i)); 
    } 
</script> 
</html> 

你應該通過兩個概念來理解這個事情

1)封閉裝置

2)JavaScript是單螺紋和同步。那麼它如何處理事件?

下面是它在你的代碼發生的事情:

==> for循環被同步執行,因爲它是JavaScript引擎後一部分的JavaScript處理事件隊列是一個FIFO(先入先出)

==>當對於i的循環結束值爲三保留在存儲器中,直到在函數內部它執行

==>每個花費值3並將其打印時間。

+0

我邀請你聊天 –

1

當這個button被監聽事件,當時的inodes.length -1是2。因爲循環已經完成它的執行並且設置值爲i爲2.

所以它是可安裝的You clicked element #3

這些問題的出現是因爲scope & closure

創建IIFE和傳遞的i值。

希望這個片段將是有益的

var nodes = document.getElementsByTagName('button'); 
    for (var i = 0; i < nodes.length; i++) { 
    (function(i){ 
    nodes[i].addEventListener('click', function() { 
     console.log('You clicked element #' + i); 
    }); 
}(i)) 

    } 

入住這jsfiddle

+0

請你詳細解釋我的情況是什麼問題?謝謝 –

1

這是使用jQuery的其他方式。

$("button").each(function(e) { 
    $(this).data("number", e); 
}).bind("click", function(e) { 
    console.log("You clicked element #" + $(this).data("number")); 
}); 

https://jsfiddle.net/ChaHyukIm/uxsqu70t/3/