通过包含的字符串查找对象
Finding objects by contained string
我正试图通过其中包含的字符串来选择某些对象。
例如,如果我定义了一个单词数组,比如说:
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/
相关文章:
- Javascript:根据对象的嵌套数组中的值,在数组中查找对象的索引
- 正在数组中查找对象
- 在prototypejs中查找对象的类
- 通过知道对象的id在JSON中查找对象
- Javascript在JSON中查找对象(我使用Angular)
- 查找对象数组是否包含其中一个标记的最快方法
- 如何将查找对象值传递到FetchXml查询中
- JavaScript-通过类似的属性查找对象,并将其推送到一个新的数组中
- 通过匹配 - Javascript/AngularJS 中的参数来查找对象
- 正在查找对象集合的最大值
- 根据Angular JS中的属性值在列表中查找对象
- 在下划线中的对象中查找对象中的重复项
- 如何使用正则表达式查找对象成员名称
- 通过包含的字符串查找对象
- 在 Firebase 中通过对象的唯一 id 查找对象
- 在 javascript 中查找对象的类型
- 查找对象树中特定字段值的所有出现
- 如何在javascript数组中按键和值查找对象的索引
- 使用 Javascript/React.js 查找对象的数组索引
- 查找对象数组(Angularjs)中是否存在值