Javascript:在复选框上更改标签背景颜色 [英] Javascript: Change label background color on checkbox

查看:187
本文介绍了Javascript:在复选框上更改标签背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图根据复选框的选中/取消选中的状态更改表格中每个复选框中的标签的背景颜色。到目前为止,我得到它最初更改,但它不会改变,当我取消选中:

I am trying to change the background color of a label in each checkbox in a form based on the checked/unchecked state of the checkbox.So far I got it to change initially, but it won't change back when I uncheck:

http://jsfiddle.net/7wnCL/ 4 /

javascript:

javascript:

function statecheck(layer) {
var myLayer = document.getElementById(layer);
 if(myLayer.checked = true){
 myLayer.style.backgroundColor = "#bff0a1";
 } else {
 myLayer.style.backgroundColor = "#eee";
 };
}

html:

<form action="" method="get">
<label title="Alabama" id="Alabama"><input type="checkbox" value="checkbox" onchange="statecheck('Alabama')" />AL</label>
<label title="Alaska" id="Alaska"><input type="checkbox" value="checkbox" onchange="statecheck('Alaska')" />AK</label>
<label title="American Samoa" id="AmericanSamoa"><input type="checkbox" value="checkbox" onchange="statecheck('AmericanSamoa')" />AS</label>
</form>

css:

label {
margin:0px 2px 4px 2px; 
padding: 1px;
background-color: #eee;
display: block;
width: 50px;
}


推荐答案

http://jsfiddle.net/7wnCL/20/

myLayer.checked = true

是分配,而不是条件。

is an assignment, not a condition.

if (myLayer.checked = true)

每次被评估为

if (true)

else部分永远不会被执行。所以改成:

And the else part will never be executed. So change it to:

if (myLayer.checked === true)

此外,您应检查输入,而不检查没有任何选中属性的图层:

Also, you should check for the input, and not for the layer, which doesn't have any checked property:

if (myLayer.childNodes[0].checked === true)

这篇关于Javascript:在复选框上更改标签背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆