我有一个复选框+标签列表。我希望在选中复选框时更改列表项的背景颜色。目前,当选中该复选框时,整个列表会更改背景颜色,而我只希望更改单个项目的背景颜色。谢谢你的帮助!
代码:
names = ["Dave","Bob","Chuck"];
var numberOf = names.length;
//Log the number of players and their names to the console.
console.log("You have " + numberOf + " recent players, and their names are " + names);
//Players List
var text = "<ul>";
for (i = 0; i < numberOf; i++) {
text += "<li class='playerListItem'><label><input type='checkbox' class='playerCheckbox'>" + names[i] + "</label></li>";
}
text += "</ul>";
document.getElementById("recentPlayersContainer").innerHTML = text;
//Changes background of currently selected playe
$('input.playerCheckbox').on('change', function(event) {
$('li.playerListItem').css('backgroundColor', 'rgba(255,102,51,0.15)');
});
});
答案 0 :(得分:1)
你可以这样做:
$('input.playerCheckbox').on('change', function(event) {
$(this).closest("li").css('backgroundColor', 'rgba(255,102,51,0.15)');
});
也许值得补充的是,取消选中此复选框后,这不会删除背景颜色。因此,我只会使用您可以删除并适用的类。
答案 1 :(得分:1)
$('input.playerCheckbox').on('change', function(event) {
$(this).closest('li.playerListItem').css('backgroundColor', 'rgba(255,102,51,0.15)');
});
答案 2 :(得分:1)
jQuery不够
$('#recentPlayersContainer').append(
$('<ul />').append(
$.map(["Dave","Bob","Chuck"], function(player) {
var check = $('<input />', {
'class' : 'playerCheckbox',
type : 'checkbox',
on : {
change : function() {
$(this).closest('li')
.css('backgroundColor', this.checked ? 'rgba(255,102,51,0.15)' : "");
}
}
}),
lbl = $('<label />', {text : player}),
li = $('<li />', {'class' : 'playerListItem'});
return li.append( lbl.prepend( check ) );
})
)
);
答案 3 :(得分:1)
在事件监听器上使用'this'关键字。
$('input.playerCheckbox').on('change', function(event) {
// 'this' below refers to the clicked element. the parents() function selects only its parent's <li>
$(this).parents('li').css('backgroundColor', 'rgba(255,102,51,0.15)');
});