如何更改选择器:包含完全匹配一个?

时间:2015-10-06 11:47:32

标签: javascript jquery

我有一行

$('#custom-table tr > td:nth-child(1):contains('+val+')').closest('tr').show();

并希望找到一种方法来获得相等或完全匹配,而不是包含。

2 个答案:

答案 0 :(得分:1)

您可以使用 filter() text()



var val = 'abc';
$('#custom-table tr > td:nth-child(1)').filter(function() {
  return $.trim($(this).text()) == val;
  // get text content using text() and compare
  // and use $.trim() for removing whitespace from the beginning and end of a string.
}).closest('tr').show();

#custom-table tr {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="custom-table">
  <tr>
    <td>abc</td>
    <td>absc</td>
  </tr>
  <tr>
    <td>abcd</td>
    <td>abcd</td>
  </tr>
  <tr>
    <td>abc</td>
    <td>absc</td>
  </tr>
  <tr>
    <td>abcd</td>
    <td>abcd</td>
  </tr>
</table>
&#13;
&#13;
&#13;

更新:完全相同的行为

&#13;
&#13;
var val = 'abc';
$('#custom-table tr > td:nth-child(1)').filter(function() {
  return $(this).text().indexOf( val)  != -1;
  // get text content using text() and compare
  // and use indexOf() for checking string contains the value.
}).closest('tr').show();
&#13;
#custom-table tr {
  display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="custom-table">
  <tr>
    <td>abc</td>
    <td>absc</td>
  </tr>
  <tr>
    <td>abcd</td>
    <td>abcd</td>
  </tr>
  <tr>
    <td>abc</td>
    <td>absc</td>
  </tr>
  <tr>
    <td>abcd</td>
    <td>abcd</td>
  </tr>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

$('#custom-table tr > td:nth-child(1)').find("*").filter(function() {
    return $(this).text() === val;
}).closest('tr').show();