Jquery搜索文本查找元素并单击

时间:2017-05-15 17:56:13

标签: jquery html-table

我正在尝试在HTML页面中搜索文本并找到该文本的元素(测试)并对其执行单击事件。所以就是这样(数据id =" 337"变化所以我不能具体。

<table>
  <tr data-id="337" style="cursor: move" class="ui-sortable-handle">
    <td>
      <a href="/locations/1371/Test_Life/337" data-update="#TestLife">Test</a>
    </td>
  </tr 
</table>

这是在表格

我认为这样可行,但它没有运行

$("tr td:contains('test')").each(function() {
  $(this).trigger('click');
})

4 个答案:

答案 0 :(得分:2)

在您的情况下,td不包含testTest,因此请将搜索字符串写为区分大小写。

&#13;
&#13;
$(function(){
  $("tr td:contains('Test')").each(function(){
$(this).trigger('click');
   console.log($(this));
})
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-id="337" style="cursor: move" class="ui-sortable-handle">
            <td>
            <a href="/locations/1371/Test_Life/337" data-update="#TestLife">Test</a>  
            </td>
            <td>
            <a href="/locations/1373/Test_Life/337" data-update="#TestLife">test</a>  
            </td>
    </tr
        </table>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

:包含区分大小写。 尝试:

$("tr td:contains('Test')").each(function() {
  $(this).trigger('click');
})

答案 2 :(得分:1)

$("tr td a:contains('Test')").each(function() {
  $(this).trigger('click');
})

答案 3 :(得分:1)

正如其他人所指出的那样,:contains区分大小写。但如果你不想要它,你可以通过以下方式更改默认值:

jQuery.expr[':'].contains = function(a, i, m) {
  return jQuery(a).text().toUpperCase()
      .indexOf(m[3].toUpperCase()) >= 0;
};

此外,请确保您的each()函数位于绑定的单击事件之后,因此在将click事件绑定到元素之前它不会运行。

here