繁体   English   中英

仅在包含某些特定单词的情况下隐藏div

[英]Hide a div only if it contains some specific words

假设有很多具有相同类的div,它们将内容动态显示为链接。 我怎样才能只删除/隐藏那些包含“体育”,“电视”,“航空公司”等字样的div?

例如

<div class="ns2-category">
    <a href="#">Sports</a>
</div>
<div class="ns2-category">
    <a href="#">Sports</a>
</div>
<div class="ns2-category">
    <a href="#">Magazine</a>
</div>
<div class="ns2-category">
    <a href="#">Airlines</a>
</div>
<div class="ns2-category">
    <a href="#">Television</a>
</div>
<div class="ns2-category">
    <a href="#">Other</a>
</div>

你可以使用下面的javascript代码:

 $("div.ns2-category:has(a:contains('Sports'))").hide(); $("div.ns2-category:has(a:contains('Sports'),a:contains('Television'))").hide(); // either one OR two 

编辑:使用div添加类名,用于多个

$(document).ready(function() {
    $('.ns2-category a').each(function(i, v) {
        if(v.html().indexOf('Sport') != -1 || v.html().indexOf('Television') != -1 || v.html().indexOf('Airline') != -1) {
             v.parent().remove();
        }
    });
});

尝试这个。

基本上,我要遍历所有div,并检查它们的内容是否包含您指定的字符串。 如果是这样,我将其删除。

我建议:

 // the words that you want to hide an element based upon: var words = ['Sports', 'Television', 'Airline']; // selecting the relevant elements: $('div.ns2-category').filter(function() { // the text contained within the <a> element, with // leading/trailing white-space (if any) removed: var text = $(this).find('a').text().trim(); // if the words array contains the found text: return words.indexOf(text) > -1; // we hide the element (though remove() could be called): }).hide(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script> <div class="ns2-category"> <a href="#">Sports</a> </div> <div class="ns2-category"> <a href="#">Sports</a> </div> <div class="ns2-category"> <a href="#">Magazine</a> </div> <div class="ns2-category"> <a href="#">Airlines</a> </div> <div class="ns2-category"> <a href="#">Television</a> </div> <div class="ns2-category"> <a href="#">Other</a> </div> 

参考文献:

$("div.ns2-category:has(a:contains('Magazine'))").hide();    
$("div.ns2-category:has(a:contains('Magazine'),a:contains('Television'))").hide();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM