简体   繁体   English

通过JQuery选中/取消选中复选框的麻烦

[英]Trouble with checking/unchecking checkboxes via JQuery

Here is a JSFiddle of my problem. 这是我的问题的JSFiddle

Note I'm using JQuery 2.0.2 for this. 注意我正在为此使用JQuery 2.0.2。

I'm using a JQuery checkbox tree plug-in and when I manually click every element inside Subgroup B2 , Subgroup B2 will also become checked. 我正在使用JQuery复选框树插件,当我手动单击Subgroup B2内的每个元素时, Subgroup B2也将变为选中状态。 Conversely, if I manually uncheck one of it's children, Subgroup B2 will go to a "partial selection" state and unchecking all of the children will completely uncheck Subgroup B2 . 相反,如果我手动取消选中子级之一,则Subgroup B2将进入“部分选择”状态,而取消选中所有子级将完全取消Subgroup B2 This works great and as intended. 这很好并且按预期工作。

However, notice the buttons at the top. 但是,请注意顶部的按钮。

I'm trying to trigger these click events through code. 我正在尝试通过代码触发这些点击事件。

The first button, fires the click event on the label (which is what gets clicked when you manually click the boxes/text). 第一个按钮在标签上触发click事件(这是您手动单击框/文本时被单击的事件)。 And as you'll notice, it checks all the boxes, however Subgroup B2 remains only partially selected. 您会注意到,它选中了所有复选框,但是, Subgroup B2仅保留部分选中状态。

Clicking the button again should toggle the checkboxes off again, but it doesn't. 再次单击该按钮再次关闭复选框,但事实并非如此。 That's what button two is for. 这就是第二个按钮的用途。 For some reason to uncheck the buttons, you need to click a different element than was required to check the checkbox. 由于某些原因要取消选中按钮,您需要单击与选中复选框所需要的元素不同的元素。 This makes no sense to me. 这对我来说毫无意义。

Finally, if you mix interactions (actual clicks and the coded clicks) things start falling apart even more. 最后,如果您将各种互动(实际点击和编码点击)混合在一起,事情就会更加瓦解。

I've been working on this for hours now, and ever time there's a problem with the interactions, it's come from the checkboxes. 我已经为此工作了几个小时,而且每次交互出现问题时,它都来自复选框。

How can I get the checkboxes to respect my coded clicks as much as my manual clicks? 如何获得复选框来尊重编码点击和手动点击?

I believe the issue with the buttons comes from the triggered event bubbling up the DOM, you can use triggerHandler() instead of trigger() to avoid that, just note that this method only affects the first matched element so you need to use it in a loop: 我相信按钮的问题来自触发事件,该事件使DOM冒泡,您可以使用triggerHandler()而不是trigger()来避免这种情况,只是请注意,此方法仅影响第一个匹配的元素,因此您需要在一个循环:

$("#trigChildren").on('click', function () {
    $('#one, #two, #three').each(function () {
        $(this).parent().triggerHandler('click');
    });
});

Updated fiddle 更新的小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM