I'm trying to bind event handlers within a loop such as:
var tabs = ['one', 'two', 'three', 'four']
for(var i = 0; i < tabs.length; i++) {
alert(tabs[i]);
var id = i;
$('#' + tabs[i]).bind('click', function() {
loadTabs(id, tabs);
});
}
Which only keeps the last one bound (value 'four').
I'm trying to consolidate this code which currently does work:
$('#one').click(function() {
loadTabs(0, tabs);
});
$('#two').click(function() {
loadTabs(1, tabs);
});
$('#three').click(function() {
loadTabs(2, tabs);
});
$('#four').click(function() {
loadTabs(3, tabs);
});
Thought I might need a closure due to this post.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…