通过包含的字符串查找对象

Finding objects by contained string

本文关键字:查找 对象 字符串 包含      更新时间:2023-09-26

我正试图通过其中包含的字符串来选择某些对象。

例如,如果我定义了一个单词数组,比如说:

var searchTerms = ["apple", "banana"];

如何在一系列相同的对象中选择包含其中一个术语的对象,并从DOM中删除包含该术语的对象?例如:

<section class="node_category">
  <h3>orange</h3>
</section>
<section class="node_category">
  <h3>apple</h3>
</section>

谢谢你的帮助!

*为清晰而编辑

使用包含

例如

    if ( $(".node_category h3:contains('orange')").size() > 0  )
    {
      //if there is any node_category which has h3 that contains orange
    }

演示

var searchTerms = ["apple", "banana"];
searchTerms.forEach( function(value){
  $(".node_category h3:contains('" + value + "')").remove();
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="node_category">
  <h3>orange</h3>
</section>
<section class="node_category">
  <h3>apple</h3>
</section>

如果要删除匹配h3的父元素(section class="node_category">),请尝试

var searchTerms = ["apple", "banana"];
searchTerms.forEach( function(value){
  $(".node_category h3:contains('" + value + "')").parent().remove();
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="node_category">
  <h3>orange</h3>
</section>
<section class="node_category">
  <h3>apple</h3>
</section>

如果您想要一个灵活的解决方案,也可以使用快速搜索:https://github.com/riklomas/quicksearch

一个小例子:

 var qs=$('input#search').quicksearch('table tbody td');
 $("#append").on("click", function(e) {
     $("tr").append('<td>'+$("#search").val()+'</td>');
     qs.cache();
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.quicksearch/2.2.0/jquery.quicksearch.min.js"></script>
/* Example form */
<form>
    <input type="text" id="search">
    <input type="button" id="append" value="ajax">
</form>
/* Example table */
<table>
    <tbody>
        <tr>
            <td>Test cell</td>
            <td>Another test cell</td>
        </tr>
    </tbody>
</table>

没有jQuery

var searchTerms = ["apple", "banana"],
    nodes = [].slice.call(document.querySelectorAll('h3')); // get all h3's and convert from nodelist to array
// loop through h3's
nodes.forEach(function(node) {
    if (searchTerms.indexOf(node.textContent) !== -1) {
        //only remove h3
        node.parentNode.removeChild(node);
        // remove section as well
        // node.parentNode.parentNode.removeChild(node.parentNode);
    }
});

演示:https://jsfiddle.net/5hb4qwmL/