我试图做一个简单的click函数,但是当我这样做时,它将触发数组中有多少个项目的确切时间。因此,如果单击该按钮,则会显示它触发3次,因为数组中有3个项(湖,腔,太阳)。我的问题是如何防止它触发x次?
var TeamPlayers = [{
team: 'Lakers',
Players: ['Russell', 'Clarkson', 'Ingram', 'Randle', 'Zubacs']
}, {
team: 'Cavs',
Players: ['Irving', 'Smith', 'LeBron', 'Love', 'Thompson']
}, {
team: 'Suns',
Players: ['Ulis', 'Booker', 'Warren', 'Chriss', 'Len']
}]
for (var i = 0; i < TeamPlayers.length; i++) {
var TeamPlayersVar = TeamPlayers[i].team
// console.log('outside loop',TeamPlayers[i].team);
$('.leftPlayer').append('<button class="leftButtons">' + TeamPlayers[i].team + '</button>' + '<br>')
$(document).on('click', '.leftButtons', function(){
console.log(this)
});
}
最佳答案
我建议使用id来做到这一点。那应该解决您的问题。因为点击将被注册为ID
for (var i = 0; i < TeamPlayers.length; i++) {
var TeamPlayersVar = TeamPlayers[i].team
// console.log('outside loop',TeamPlayers[i].team);
$('.leftPlayer').append('<button id="btn'+i+'" class="leftButtons">' + TeamPlayers[i].team + '</button>' + '<br>')
$("#btn"+i).click(function(){
console.log(this)
});
}