Javascript 如何基于复选框设置特定div的样式

Javascript 如何基于复选框设置特定div的样式,javascript,html,css,checkbox,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" onc

好的,我想做的是根据所单击的复选框更改特定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 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

      }
    }
  }
功能测试(){
var checkbox=document.getElementsByClassName('the-checkbox');
对于(变量i=0;i
您走在正确的轨道上

复选框的
是复选框和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"; 
}
@TilwinJoy:-)复制粘贴的乐趣。