我正在尝试创建一个简单的单击功能,但是当我这样做时,它会触发数组中有多少项的准确次数。因此,如果我单击按钮,我会显示它会激活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)
});
}
答案 0 :(得分:1)
我建议使用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)
});
}
答案 1 :(得分:0)
这种情况正在发生,因为您正在为一个类分配单击侦听器,并且有3个具有指定类名的元素,为了使其仅工作一次,请使用ID或使用唯一的类名
答案 2 :(得分:0)
您只需要将您的点击处理程序代码放在循环之外,即
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>')
}//for()
$(document).on('click', '.leftButtons', function(){
console.log(this)
});