使用字符串数组复选框

Check checkboxes using array of string

本文关键字:复选框 数组 字符串      更新时间:2023-09-26

用户可以提供字符串数组,我想在表中查找,并在找到字符串之一时检查与表行相关的复选框。

我可以看到$("#activelisttable tr:contains(" + substr[i] + ")")包含一个<tr>,但它根本不在.each函数中。

下面是完整的代码:

     $("#savelistactive").click(function() {
            var substr = $("#listtextactive").val().split("'n");
            for (var i = 0; i < substr.length; i++) 
            {
                $("#activelisttable tr:contains(" + substr[i] + ")").each(function(item) {
                    $(this).children("input").prop('checked', true);
                });
            }
            $("#background").fadeOut("slow");
            $("#listactive").fadeOut("slow");
        });

提琴链接:http://jsfiddle.net/5WVwe/

问题概述:

问题在于for循环内的选择器。@NobleMushtak建议您将原始小提琴中的.each()更改为:

$("#activelisttable tr:contains(" + substr[i] + ")").children("input").prop('checked', true);
这是一个很好的建议。但是,由于没有看到您的标记,因此不清楚您使用的确切HTML结构。根据您的小提琴,您的HTML标记包含<tr> 's,然后在其中包含<th> 's:
        <tr>
            <th>
                <input type="checkbox" class="selectall" />
            </th>
            <th>name</th>
        </tr>

这意味着没有<tr>类型为input.children()

解决方案:

.children()改为.find():

$("#activelisttable tr:contains(" + substr[i] + ")").find("input").prop('checked', true);

.find()所有嵌套元素进行深度搜索,而.children()只会再遍历一层。

更新JSFiddle

参考文档:

.find()

.children()