2014-06-20 21 views
0

好了,所以我想要做的是改变特定的div的基础上被点击复选框的风格..如何风格基础上checkboxs特定的div

我有几个checkboxs这样的...

<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"> 

值= “1” ID = “面板-1,ID =” 面板-2 “ID =” 面板-2" 等

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

当一个复选框被点击,例如值=“1”,我希望它改变div的颜色与“ID面板-1”。

我也需要这个工作时,多个复选框被选中,因为这是为了造型我的“删除条目”功能。

我有麻烦的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

您是在正确的轨道

复选框的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"; 
} 
+0

这是为什么线不正确..? :D –

+0

@TilwinJoy :-)复制粘贴的乐趣。 – Nivas