[英]How to style specific divs based on checkboxs
Okay so what I want to do is change the style of specific divs based on checkboxes being clicked.. 好吧,所以我想做的就是根据被单击的复选框更改特定div的样式。
I have several checkboxs like this... 我有几个这样的复选框...
<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">
Each of these correspond to a div... 这些每个都对应一个div。
<div class="panel-heading" id="panel-1">
<div class="panel-heading" id="panel-2">
<div class="panel-heading" id="panel-3">
value="1" with id="panel-1, id="panel-2"with id="panel-2" etc 值=“ 1”和ID“ =” panel-1”,ID =““窗格2””,ID =“ PANEL-2”等
These elements are dynamic and are pulled from a database. 这些元素是动态的,是从数据库中提取的。
When a checkbox is clicked for example the one with the value="1" I want it to change the colour of the div with "id panel-1". 例如,当单击一个复选框时,我希望它具有值=“ 1”的复选框来更改带有“ id panel-1”的div的颜色。
I also need this to work when multiple checkboxes are checked as this is for styling my "delete entry" functionality. 当选中多个复选框时,我也需要此功能,因为这是用于设置“删除条目”功能的样式。
I am having trouble doing this in javascript here is what I have so far... 我在用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
}
}
}
You are on the right track 您走在正确的轨道上
The value
of the checkbox is the link between the checkbox and the div. 复选框的value
是复选框和div之间的链接。 Value 1
corresponds to div panel-1
etc. So use the value to get the corresponding 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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.