更改复选框列表项的颜色

Change Color of Checkbox List Item onChange

本文关键字:颜色 列表 复选框      更新时间:2023-09-26

我有一个复选框+标签的列表。 我希望选中该复选框时列表项的背景颜色会更改。 目前,选中该复选框后,整个列表会更改背景颜色,而我只希望更改单个项目的背景颜色。 感谢您的帮助!

法典:

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)');
});
});
$('input.playerCheckbox').on('change', function(event) {
    $(this).closest('li.playerListItem').css('backgroundColor', 'rgba(255,102,51,0.15)');
});

没有足够的 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 ) );
        })
    )
);

小提琴

事件侦听器上使用"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)'); 
});
你可以

这样做:

$('input.playerCheckbox').on('change', function(event) {
  $(this).closest("li").css('backgroundColor', 'rgba(255,102,51,0.15)');
});

可能还值得补充的是,取消选中复选框时,这不会删除背景颜色。因此,我只会使用一个可以根据需要删除和应用的类。

相关文章: