jQuery-在每个复选框中获取下一个元素

jQuery - get next element inside checkbox each

本文关键字:获取 下一个 元素 复选框 jQuery-      更新时间:2023-09-26

我有一个包含以下列的表:复选框、文本、文本。。。对于每个选中的复选框,我需要获得第二个文本值,并测试是否包含一些值。

到目前为止我的代码

$('input:checkbox').each(function () {
    var current = $(this);
    if (current.is(':checked')) {
        var txt = current.next('.inf-name').text();
        if (txt.contains(inf) { ... }
    }
});

剃须刀代码:

<table class="table table-bordered table-modified">
    <thead>
        <tr>
            <th></th>
            <th>State</th>
            <th>Lookup Type</th>
            <th>Plates</th>
            <th>Notices</th>
        </tr>
    </thead>
    <tbody>
        @Html.HiddenFor(p => p.OrgUnitID, new { @Value = orgUnitId })
        @for(var ind = 0; ind < records.Count(); ++ind)
        {
            var r = records[ind];
            var i = ind;
            @Html.HiddenFor(p => p.Comp[i].State, new { @Value = @r.State })
            <tr>
                <td>@Html.CheckBoxFor(p => p.Comp[i].Checked)</td>
                <td>@r.State</td>
                @if (dict.ContainsKey(r.State)) 
                { <td class="inf-name">@dict[r.State].ToString()</td> }
                else
                { <td class="inf-name"></td> }
                <td>@Html.ActionLink(@r.Plates.ToString(CultureInfo.InvariantCulture), "Plates", new { controller = "Lookup", state = @r.State})</td>
                <td>@Html.ActionLink(@r.Notices.ToString(CultureInfo.InvariantCulture), "Plates", new { controller = "Lookup" }, new { state = @r.State })</td>
            </tr>
        }
    </tbody>
</table>

其中inf-name是第二个元素上的类。我做不到。有人知道解决方案吗?

使用next()将获得直接同级,您需要为复选框获取父项,该复选框是<td>使用nextAll().eq(1)查找下一个同级,使用.text() 获取该同级内的文本

编辑:

如果你希望你的目标使用类(提供的类以后永远不会改变),那么只需将你的代码更改为:

$('input:checkbox').each(function () {
    var current = $(this);
    if (current.is(':checked')) {
        var txt = current.next('.inf-name').eq(1).text();
        if (txt.contains(inf) { ... }
    }
});
    var currentRows = $('.table tbody tr');
                $.each(currentRows, function () {
                    $(this).find(':checkbox').each(function () {
                        if ($(this).is(':checked')) {
                            console.log($(currentRows).eq(1).val());
                        }
                    });
      });