删除所有如果文本中不包含“test”

时间:2017-11-17 10:11:51

标签: javascript jquery html google-chrome-extension

我是第一次制作Chrome扩展程序,需要一点帮助我的Javascript。

在我的弹出菜单中,我想要几个按钮。一旦有人按下此按钮,就可以按下“测试”按钮。我希望它删除不包含单词<tr>的每个"test"

我这样做是因为我使用的网站上的过滤功能非常慢。通过这种方式,我可以通过删除行而不是程序搜索所有行来更快地过滤。

这是我到目前为止所做的:

var searchString = 'TEST';
$("#tbody tr td:contains('" + searchString + "')").each(function Tester() {
  if ($(this).text() != searchString) {
    $(this).parent().remove();
  }
});
<p>Remove all rows which don't contain:</p>
<button onclick="Tester()">TEST</button>

2 个答案:

答案 0 :(得分:4)

首先不要使用内联JS。这是不好的做法。使用不引人注目的JS来附加事件处理程序。

要解决您的实际问题,请使用:contains上的remove()选择器,如下所示:

&#13;
&#13;
$('button').click(function() {
  var searchString = $(this).text();
  $("#tbody tr td:contains('" + searchString + "')").closest('tr').remove();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Remove all rows which don't contain:</p>
<button>TEST</button>

<table>
  <tbody id="tbody">
    <tr>
      <td>TEST</td>
    </tr>
    <tr>
      <td>Foo</td>
    </tr>
    <tr>
      <td>TEST</td>
    </tr>
    <tr>
      <td>Bar</td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个

$("#tbody tr td").each( function () {
    if ( $(this).text().indexOf( searchString ) == -1 ) { //notice the use of indexOf
        $(this).parent().remove();//
    }
});

或者您可以检查行text本身

$("#tbody tr").each( function () {
    if ( $(this).text().indexOf( searchString ) == -1 ) { 
        $(this).remove();//
    }
});
相关问题