我有两个相同代码的版本。 当我在此页面的代码段中添加它时,它运行得很好。但是,出于某种原因,我无法让它在我的计算机上工作。
看一下我的Dropbox version以获得一些想法。它与我在两种情况下使用的编码相同。如果选中子复选框,它应该检查父复选框,反之亦然。
你们有些想法为什么会这样吗?
$('input[type=checkbox]').click(function () {
$(this).parent().find('li input[type=checkbox]').prop('checked', $(this).is(':checked'));
var sibs = false;
$(this).closest('ul').children('li').each(function () {
if($('input[type=checkbox]', this).is(':checked')) sibs=true;
})
$(this).parents('ul').prev().prop('checked', sibs);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul class="tree" id="tree">
<li>
<input type="checkbox" name="account_settings" value="yes">Account Settings
<!-- AND SHOULD CHECK HERE -->
<ul>
<li>
<input type="checkbox" name="one" value="one">AS One</li>
<li>
<input type="checkbox" name="two" value="two">AS Two</li>
<li>
<input type="checkbox" name="user_roles" value="user_roles">Users & Roles
<!-- SHOULD CHECK HERE -->
<ul>
<li>
<input type="checkbox" name="user_role" value="add">Add</li>
<li>
<input type="checkbox" name="user_role" value="delete">Delete</li>
<!-- CHECK HERE -->
</ul>
</li>
</ul>
</li>
<li>
<input type="checkbox" name="rl_module" value="yes">RL Module</li>
<li>
<input type="checkbox" name="rl_module" value="yes">Accounting
<ul>
<li>
<input type="checkbox" name="vat" value="yes">VAT</li>
<li>
<input type="checkbox" name="bank_account" value="yes">Banking
<ul>
<li>
<input type="checkbox" name="view" value="yes">View</li>
<li>
<input type="checkbox" name="crud" value="yes">CRUD</li>
</ul>
</li>
</ul>
</li>
</ul>
&#13;
答案 0 :(得分:0)
上述代码段不起作用的原因是“事件没有附加”到元素。尝试在页面中打开调试器工具,然后在Dropbox中打开调试器工具,您会发现Dropbox的元素没有附加事件。
您可以使用on
附加事件来克服这种情况。
$('input[type=checkbox]').on('click',function () {
$(this).parent().find('li input[type=checkbox]').prop('checked', $(this).is(':checked'));
var sibs = false;
$(this).closest('ul').children('li').each(function () {
if($('input[type=checkbox]', this).is(':checked')) sibs=true;
})
$(this).parents('ul').prev().prop('checked', sibs);
});
答案 1 :(得分:0)
你试过把你的脚本放在身体后面吗? (您可以将脚本标记保留在头部加载jQuery的位置)
我使用了你的代码,只是把你的脚本放在身体之后,它工作得很好。
我有这个问题以及脚本放在身体前不会起作用。
让我知道它是否有效出你的。