多个复选框触发 js 脚本

我在 while 循环中生成了多个列表。每个列表都有一个分配给它的组 ID,并存储在一个变量中。每个列表项都有一个复选框。我希望能够在每个列表下方有一个“全选”选项。


虽然我的代码适用于单个列表,但对于多个列表,它只适用于其中一个。我相信这是因为每个列表在复选框上都有相同的类名。我可以将组 ID 附加到每个类,但这意味着将脚本放在 while 循环中,我过去被告知这是不正确的。


我当前每个列表项的复选框代码示例是


<input type="checkbox" name="ids[1881:b4568df26077653eeadf29596708c94b]" id="cl-checkbox1881:b4568df26077653eeadf29596708c94b" class="cl-checkbox" onclick="clRowSelection(this);" />

每组可能有多个。


我的“全选”复选框代码是


<input type="checkbox" name="cl_select_all_1" id="cl-checkall" />

每个组都会有一个。


我的脚本是


jQuery("#cl-checkall").change(function() {

    jQuery(".cl-checkbox").prop('checked', jQuery(this).prop("checked"));

});


jQuery('.cl-checkbox').change(function() { 

    if(false == jQuery(this).prop("checked")) {

        jQuery("#cl-checkall").prop('checked', false);

    }

    if (jQuery('.cl-checkbox:checked').length == jQuery('.cl-checkbox').length ){

        jQuery("#cl-checkall").prop('checked', true);

    }

});

我读到我可以使用 data-groupID="mygroupID" 之类的东西,然后使用 $(this) 将其传递到脚本中,这样它就知道选择了哪个复选框。


我相信我需要为列表执行此操作:


<input type="checkbox" name="ids[1881:b4568df26077653eeadf29596708c94b]" id="cl-checkbox1881:b4568df26077653eeadf29596708c94b" class="cl-checkbox" data-groupID="mygroupID" onclick="clRowSelection(this);" />

这对于全选:


<input type="checkbox" name="cl_select_all_1" id="cl-checkall" data-groupID="mygroupID"/>

但我坚持如何添加


$(this).data('groupID')

到脚本让它工作。


我对使用 $(this) 作为解决方案的理解可能完全错误!


慕容森
浏览 189回答 1
1回答

噜噜哒

在您的全选更改处理程序中,您可以只选择与您当前匹配的输入 groupIDjQuery(".cl-checkall").change(function() {&nbsp; &nbsp; jQuery('.cl-checkbox[data-groupID="' + jQuery(this).data("groupid") + '"]')&nbsp; &nbsp; &nbsp; &nbsp; .prop('checked', jQuery(this).prop("checked"));});这实际上是您已经拥有的,但我们将数据选择器添加到 jQuery 搜索以排除页面上的其他复选框。(jQuery(this).data("groupid")jQuery 要求数据属性名称为小写)将返回更改元素的数据属性,并且[data-groupID="x"]只会匹配具有 groupID 的元素x(由于您现在有多个,您可能还想开始在全选复选框上使用一个类而不是一个 ID,我已将其更改为 using .cl-checkall)可以将相同的更改应用于单个复选框侦听器,仅选择具有匹配数据属性的全选。jQuery('.cl-checkbox').change(function() {&nbsp;&nbsp; &nbsp; if(false == jQuery(this).prop("checked")) {&nbsp; &nbsp; &nbsp; &nbsp; jQuery('.cl-checkall[data-groupID="' + jQuery(this).data("groupid") + '"]').prop('checked', false);&nbsp; &nbsp; }&nbsp; &nbsp; if (jQuery('.cl-checkbox[data-groupID="' + jQuery(this).data("groupid") + '"]:checked').length == jQuery('.cl-checkbox[data-groupID="' + jQuery(this).data("groupid") + '"]').length ){&nbsp; &nbsp; &nbsp; &nbsp; jQuery('.cl-checkall[data-groupID="' + jQuery(this).data("groupid") + '"]').prop('checked', true);&nbsp; &nbsp; }});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript