使用 JQuery 确定表是否包含具有特定内容的行

Using JQuery to determine if a table contains a row with specific content

本文关键字:包含具 JQuery 是否 使用      更新时间:2023-09-26

我有这个html表(大大简化了以保护无辜者)...

<table id="codeList">
<thead> 
    <tr>
        <th>Code</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>Code1 <input type="hidden" name="code1" value="123"/></td>
    </tr>
        <tr>
        <td>Code2 <input type="hidden" name="code2" value="456"/></td>
    </tr>
    <tr>
        <td>Code3 <input type="hidden" name="code3" value="789"/></td>
    </tr>
</tbody>

。我正在尝试在 javascript 方法中确定代码是否已经在表中......

if (!$('#codeList >tbody').is( ":contains('456')")) {
    $("#codeList > tbody:last").append("<tr>" +
    "<td> Code2 <input type='hidden' name='code2' value='456'/></td>" +
    "</tr>");
}

。这是行不通的。 基本上,我需要一个 JQuery 表达式,它可以搜索表的行,检查每个隐藏字段的值以查看它是否已经存在并返回 true/false,或者至少出于 javascript 条件的目的表现得像真/假。 这与我看到的大多数方案略有不同,我需要确定行是否存在,然后对表执行操作。 大多数人希望选择确实存在的行,然后对它们执行操作。

不要对属性值使用 :contains,请使用属性等于选择器:

if (!$('#codeList input[value="456"]').length) {
   // do something
}

也就是说,选择具有该值的任何输入,这些输入是#codeList的后代,如果没有找到,则.length将为 0...

if (!$("#codeList input[value='456']")[0]) {
    $("#codeList > tbody:last").append("<tr>" +
    "<td> Code2 <input type='hidden' name='code2' value='456'/></td>" +
    "</tr>");
}
if (!$('#codeList input[value="456"]').length) {
 $("#codeList > tbody:last").append("<tr>" +
  "<td> Code2 <input type='hidden' name='code2' value='456'/></td>" +
  "</tr>");
}