gpt4 book ai didi

javascript - 检查是否在页面加载时选择了复选框并向父 html li 添加一个类

转载 作者:行者123 更新时间:2023-11-30 09:08:24 25 4
gpt4 key购买 nike

我正在寻找一种方法来使用原型(prototype),这个 js,需要加载页面并使用给定的 id 交互所有元素(输入 - 复选框,在这种情况下)并将一个类分配给它的父级 <li></li>

JS 是:

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 = '';}
*/

}

与这个 JS 交互的 HTML(它的一部分)是:

<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" 添加到 <li id="selectedAuthorities-4_1li">

最佳答案

要在页面加载时运行一些东西(实际上,当 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')

关于javascript - 检查是否在页面加载时选择了复选框并向父 html li 添加一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2822571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com