检查是否在页面加载时选中了复选框,并将类添加到父html li

时间:2010-05-12 20:36:28

标签: javascript html checkbox iteration prototypejs

我正在寻找一种方法来处理原型,这个js,需要加载页面并使用给定的id对所有元素(输入 - 复选框,在本例中)进行交互,并为其父{{}分配一个类。 1}}

JS是:

<li></li>

与此JS交互的HTML(片段)是:

function changeSelectionStyle(id) {

 var inputId = id.substr(0,id.length-2);
 if(document.getElementById(inputId).checked){document.getElementById(id).className = 'yes';}
 alert(document.getElementById(inputId).checked);

 /*
  * if(document.getElementById(id).className != 'yes'){
  * document.getElementById(id).className = 'yes';
  *  } else{document.getElementById(id).className = '';}
  */

}

迭代后,选中复选框,必须将<li id="selectedAuthorities-4_1li"> <input type="checkbox" id="selectedAuthorities-4_1" name="selectedAuthorities" value="ROLE_ADD_COMMENT_TO_CV" checked="checked" onclick="changeSelectionStyle(this.id + 'li'); checkFatherSelection(this.id);"> <a href="#" onclick="document.getElementById('selectedAuthorities-4_1').click(); return false;"> Agregar comentario <samp><b></b>Permite agregar comentario en el detalle</samp> </a> </li> 添加到class="yes"

2 个答案:

答案 0 :(得分:3)

要在页面加载时运行某些东西(实际上,当DOM准备就绪时),请使用:

document.observe("dom:loaded", function() {
    init()
});

然后,您可以选择所有输入,如果已选中,则将类名添加到其父级:

function init() {
    $(document.body).select('input').each(function(element) {
        if(element.checked) {
            element.up().addClassName('yes')
        }
    })
}

如果你想更具体并选择LI(如果有其他标记包装输入)你可以替换:

element.up('li').addClassName('yes')

答案 1 :(得分:1)

假设您可以使用原型,并且您可以更改生成的HTML,我建议您为每个复选框提供一个类。这就是我的想法。

<li id="selectedAuthorities-4_1li">
   <input type="checkbox" class="example_class">
...
</li>

然后使用原型,您可以使用CSS选择器$$

遍历每个复选框
$$('.example_class');

假设您要将“selected”类添加到复选框parent,您可以执行以下操作:

$$('.example_class').each(function(element) {
    if (element.checked) {
        element.up().addClassName('selected');
    }
});

要在dom加载完成后运行所有这些代码,您可以将所有这些代码包装在此观察者中:

document.observe("dom:loaded", function() {
    //the above code here
});

如果您愿意使用原型(或任何javascript框架),花一些时间学习它,您将获得比您没有它生成的代码更好的代码