好的,我想要做的是根据点击的复选框更改特定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
}
}
}
答案 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";
}