如何根据复选框设置特定div的样式

时间:2014-06-20 13:22:04

标签: javascript html css checkbox

好的,我想要做的是根据点击的复选框更改特定div的样式。

我有几个像这样的复选框......

<input  type="checkbox" class="the-checkbox" onchange="test()" value="1">
<input  type="checkbox" class="the-checkbox" onchange="test()" value="2">
<input  type="checkbox" class="the-checkbox" onchange="test()" value="3">

每个都对应一个div ...

<div class="panel-heading" id="panel-1">
<div class="panel-heading" id="panel-2">
<div class="panel-heading" id="panel-3">

value =“1”,id =“panel-1,id =”panel-2“,id =”panel-2“等

这些元素是动态的,是从数据库中提取的。

当单击一个复选框时,例如值为“1”的复选框,我希望它用“id panel-1”更改div的颜色。

当选中多个复选框时,我也需要这个,因为这是为了设置我的“删除条目”功能。

我在javascript中这样做有困难这是我到目前为止...

function test(){

    var checkboxes = document.getElementsByClassName('the-checkbox');

    for (var i=0 ; i < checkboxes.length; i++) {
      if (checkboxes[i].checked) {

      var cn = document.getElementsByClassName('panel-heading')[i].id
      cn.style.backgroundColor = "red"; // I know this line is incorrect

      }
    }
  }

1 个答案:

答案 0 :(得分:0)

你走在正确的轨道上

复选框的value是复选框和div之间的链接。值1对应div panel-1等。因此,使用该值来获取相应的div:

correspondingDiv = div with id ("panel-" + value of selected checkbox)


if (checkboxes[i].checked) {
    //Get the value of the checkbox
    var val = checkboxes[i].value;

    //Since the value is the link between the checkbox and the div, 
    //use it to get the corresponding div
    var correspondingDiv = document.getElementById("panel-" + val);

    //And apply the background color
    correspondingDiv.style.backgroundColor = "red"; 
}