除了一个异常(exception),我可以让后续代码按照我希望的方式工作。 当我选中复选框时,div 的背景颜色会从#fff 更改为#ffe600。我遇到的问题是提交表单和刷新页面时背景颜色恢复为#fff。我希望在提交表单后刷新页面时,背景颜色保持#ffe600。页面刷新后该复选框仍处于选中状态,但 div 背景颜色恢复为#fff。有谁知道刷新页面时是否可以保持 div 背景颜色#ffe600。这真是被难倒了。
function myFunction(x, _this) {
if (_this.checked) {
x.style.backgroundColor = '#ffe600';
} else {
x.style.backgroundColor = '#fff';
}
}
#product1 {
background-color: #fff;
padding: 3px 5px 3px 7px;
margin-top: 6px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="product1">
<label class="chk">
<input type="checkbox" onChange="myFunction(product1, this)" name="select_product" value="Y" />Label goes here.</label>
</div>
谢谢!
最佳答案
一个选项是使用 jquery 检查加载,然后突出显示当前选中的框。
$('input[type=checkbox]').each(function(){
if($(this).is(':checked'))
$(this).parent().parent().css('backgroundColor','#ffe600');
else
$(this).parent().parent().css('backgroundColor','#fff');
});
function myFunction(x, _this) {
if (_this.checked) {
x.style.backgroundColor = '#ffe600';
} else {
x.style.backgroundColor = '#fff';
}
}
#product1 {
background-color: #fff;
padding: 3px 5px 3px 7px;
margin-top: 6px;
}
#product2 {
background-color: #fff;
padding: 3px 5px 3px 7px;
margin-top: 6px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="product1">
<label class="chk">
<input type="checkbox" onChange="myFunction(product1, this)" name="select_product" value="Y" />Label goes here.</label>
</div>
<div id="product2">
<label class="chk">
<input checked type="checkbox" onChange="myFunction(product2, this)" name="select_product2" value="V" />Label goes here 2.</label>
</div>
关于javascript - 切换复选框 div 或标签的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39733193/