我想自动取消选中或选中子项的复选框:
HTML:
<ul>
<li>1 <input type='checkbox' /></li>
<ul>
<li>1.1 <input type='checkbox'' /></li>
</ul>
<ul>
<li>1.1.1 <input type='checkbox' /></li>
</ul>
</ul>
Javascript:
$('li input').change(function(){
if($(this).is(":checked")){
$(this).parent().next().children("li").children("input").attr("checked", true);
console.log("checked")
}else{
$(this).parent().next().children("li").children("input").attr("checked", false);
console.log("not checked")
}
})
但它只适用于第一次出现。我不明白为什么,因为1.1更改并且事件更改没有触发
谢谢
最佳答案
如果您将 HTML 更正为以下内容:
<ul>
<li>1 <input type="checkbox" />
<ul>
<li>1.1 <input type="checkbox" />
<ul>
<li>1.1.1 <input type="checkbox" /></li>
</ul>
</li>
</ul>
</li>
</ul>
然后下面的 jQuery 就可以工作了:
$('input:checkbox').change(
function(){
var state = this.checked ? true : false;
$(this).next('ul').find('input:checkbox').prop('checked', state);
});
HTML 的问题在于 ul
元素不是另一个 ul
或 ol
元素的有效子元素。 ul
(和 ol
)的唯一有效子元素是 li
元素,一切都无效,除非它是包含在 li
中。
引用文献:
-
:checkbox
selector . -
find()
. -
prop()
.
关于javascript - 选中列表中的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13893184/