我正在使用 Asp.Net CheckBoxList 控件,我在 li 元素中有很多复选框。如果在其中选中复选框,我想更改 li 元素的背景颜色。我用 css 和 jquery 尝试了很多东西,但我做不到。
注意:当我单击复选框时,下面给出的一些答案有效。但是当页面回发时,选中的框将变为默认 View 。
<ul id="ContentPlaceHolder1_CheckBoxList1">
<li><input id="c1" type="checkbox" name="c1" value="57" /><label for="c1">aaaaaaaaa</label></li>
<li><input id="c2" type="checkbox" name="c2" value="94" /><label for="c2">bbbbbbbbbb</label></li>
<li><input id="c3" type="checkbox" name="c3" value="121" /><label for="c3">cccccccccc</label></li>
</ul>
我的一些尝试:
<!-- 1 -->
var ccc = function () {
$("input:checked").parent("li").css({"color": "white", "background-color": "blue"});
};
ccc();
$( "input[type=checkbox]" ).on( "click", ccc );
<!-- 2 -->
$(":checkbox").click(function(){
$(":checked").parent().css({"color": "white", "background-color": "blue"});
});
/*1*/
li < input[type=checkbox]:checked {
background-color:aqua;
}
/*2*/
li:has( input[type="checkbox"]:checked) {
background: #000;
border-color: green;
color: white;
}
最佳答案
使用 jquery is()
函数和elem.closest()
功能。您可以使用更改事件根据输入条件添加或删除类
$(document).on('change','#ContentPlaceHolder1_CheckBoxList1 input[type=checkbox]',function(){
if($(this).is(':checked')){
$(this).closest('li').addClass('checked_class')
}else{
$(this).closest('li').removeClass('checked_class')
}
})
.checked_class{
border:1px solid red;
/*add your desgin properties*/
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="ContentPlaceHolder1_CheckBoxList1">
<li>
<input id="c1" type="checkbox" name="c1" value="57" />
<label for="c1">aaaaaaaaa</label>
</li>
<li><input id="c2" type="checkbox" name="c2" value="94" /><label for="c2">bbbbbbbbbb</label></li>
<li><input id="c3" type="checkbox" name="c3" value="121" /><label for="c3">cccccccccc</label></li>
</ul>
关于javascript - 如何更改已选中复选框的父元素的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55199465/