当前位置: 代码迷 >> JavaScript >> 无法在每个()周期内选择复选框
  详细解决方案

无法在每个()周期内选择复选框

热度:81   发布时间:2023-06-05 14:04:39.0

我试图遍历每个文本输入字段并找出分配给它的复选框是否被选中。 我在选择each()周期内的复选框时遇到了麻烦。

我的HTML:

<table>
        <tbody>
                <tr>
                    <td style="vertical-align: top;">
                        <label for="MainTemplate" class="">Hlavná ?ablóna:</label>
                    </td>
                    <td>
                        <input name="MainTemplate" class="input mainTemplate" value="" style="width: 10em;" type="text"> <br> <table>

    <tbody><tr>         <td>            <input name="MainTemplateInheritCheckbox" class="input inheritCheckbox" value="1" checked="checked" type="checkbox">        </td>       <td style="font-size: 0.9em;">          <label for="MainTemplateInheritCheckbox">hodnoda sa zdedí z vy??ej úrovne</label>       </td>   </tr>

</tbody></table>
                        <br>
                    </td>
                </tr>
                <tr>
                    <td style="vertical-align: top;">
                        <label for="Lector" class="">?kolite?:</label>
                    </td>
                    <td>

                        <input name="Lector" class="input lector" value="" style="width: 10em;" type="text"> <br> <table>   <tbody><tr>         <td>            <input name="LectorInheritCheckbox" class="input inheritCheckbox" value="1" checked="checked" type="checkbox">      </td>       <td style="font-size: 0.9em;">          <label for="LectorInheritCheckbox">hodnoda sa zdedí z vy??ej úrovne</label>

        </td>   </tr> </tbody></table>
                        <br>
                    </td>
                </tr>
</table>

我的jQuery代码:

        $("input[type=text]").each(function() {
            // here I need to find out whether the checkbox is checked or not
        });

我试过了,但即使选中了复选框,它也会返回false:

alert($(this).next().next().children("input[type=checkbox]:first").is(":checked"));

尝试$(this).next('table').find('input[type=checkbox]:first')is(':checked');

您可能还可以通过名称获得它,因为它们是相关的。

var cbName = '#' + $(this).attr('name') + 'InheritCheckbox';
$(cbName).is(':checked');

这两个都有些脆弱,并且取决于DOM中或元素名称之间的关系,尽管我怀疑后者随着时间的推移可能会更加稳定。

试试这个(获取包含表的行并搜索该元素内的复选框):

$("input[type=text]").each(function() {
    alert($(this).closest("tr").find("input[type=checkbox]:first").is(":checked"));
}); 

尝试

$("input[type=checkbox]:first",$(this).parent()).is(":checked")

$("input[type=text]").each(function()
{
    alert($(this).closest("td").find("input[type=checkbox]").attr("checked"));
}); 
  相关解决方案