2014-11-23 23 views
0

我有这样的HTML表(大大简化,以保护无辜者)的行...使用jQuery,以确定是否一个表中包含的具体内容

<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条件下表现为true/false 。这与我看到的大多数情况有点不同,我需要确定一行是否不存在,然后在表上进行操作。大多数人想要选择存在的行并对其执行操作。

回答

2

不要使用:contains属性值,使用attribute equals selector

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

即选择与值是#codeList后代,如果没有找到,然后.length将是0,任何输入...

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