gpt4 book ai didi

javascript - li 输入复选框 : how to get checked state javascript

转载 作者:行者123 更新时间:2023-12-03 05:34:54 25 4
gpt4 key购买 nike

我可以访问每个 li[i] 返回您在图片中看到的内容。例如,li[i].innerText 返回 business。如何获取每个元素的 checked 状态?

element iteration

//loop through li elements in categories to add listeners
for(var i = 0 ; i < li.length; i++){
(function(i){
li[i].addEventListener('click', function(event) {
event.preventDefault();

//disallow repeats
if(checkedItems.indexOf(li[i].innerText) == -1){
checkedItems[counter] = li[i].innerText;
counter++;
console.log("added");
}

console.log(li[i].checked); //undefined
//remove element if unchecked from array
if(li[i].checked){
var index = checkedItems.indexOf(li[i].innerText);
console.log(li[i].innerText +": " + index);
checkedItems.splice(index, 1);
console.log("disabled");
counter--;
}
console.log(checkedItems);
});
}(i));

}

最佳答案

您需要获取对 input 元素的引用,可以按如下方式执行:

var input = this.querySelector('input[type=checkbox]');

...然后您可以使用input.checked:

var li = document.querySelectorAll('li');

for(var i = 0 ; i < li.length; i++){
li[i].addEventListener('click', function(event) {
//event.preventDefault();
var input = this.querySelector('input[type=checkbox]');
console.log(this.textContent.trim(), input.checked);
});
}
<ul>
<li>
<span>test</span>
<input type="checkbox">
</li>
</ul>

关于javascript - li 输入复选框 : how to get checked state javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40775387/

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