检查表jquery上是否存在具有特定td的行

时间:2018-07-29 23:58:47

标签: jquery

我想检查一行是否具有带有特定标题和年份的td。 这是我的函数,问题是title2和year2设置为undefined。 如何正确获取单元格值?

var table = $("#mainTable");
        var exist;
        $(table).find("tr").each(function () {
            var title2 = $(this).find("td:nth-child(1)").html();
            var year2 = $(this).find("td:nth-child(2)").html();
            if (title == title2 && year == year2)
                exist = true;

        });
        return exist;

和我的桌子:

<div class="table-responsive">
    <table class="table table-condensed table-bordered table-striped table-hover" id="mainTable">
        <thead>
            <tr>
                <th scope="col">Id</th>
                <th scope="col">Emri</th>
                <th scope="col">Viti</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var subject in Model.Subjects)
            {
                <tr>
                    <td id="subjectId">@subject.Id</td>
                    <td id="subjectTitle">@subject.Title</td>
                    <td id="subjectYear"> @subject.Year</td>
                    <td>
                        <a id="add" class="add" title="Add" data-toggle="tooltip"><i class="material-icons">&#xE03B;</i></a>
                        <a id="edit" class="edit" title="Edit" data-toggle="tooltip"><i class="material-icons">&#xE254;</i></a>
                        <a id="delete" class="delete" title="Delete" data-toggle="tooltip"><i class="material-icons">&#xE872;</i></a>
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div>

2 个答案:

答案 0 :(得分:2)

可能是由于循环中包含<thead>行,而没有<td>

nth-child也不是从零开始的,因此您正在寻找错误的单元格

尝试更改为,仅搜索<tbody>

    var table = $("#mainTable");
    var exist;
    table.find("tbody tr").each(function () {
        var title2 = $(this).find("td:eq(1)").html();
        var year2 = $(this).find("td:eq(2)").html();
        if (title == title2 && year == year2)
            exist = true;
            // break the loop once found
            return false;

    });
    return exist;

最后,元素ID在定义上是唯一的。改用普通的类

答案 1 :(得分:1)

这只是一个建议,因为看来您已经在使用剃刀创建表,为什么不将标题和年份的数据属性添加到每一行。那么您可以使用选择器。

MeterFilter

这是一个小提琴演示(我用javascript代替了razor来创建表格,但您明白了)

https://jsfiddle.net/xtqnksj4/

相关问题