仅当div包含某些特定单词时才隐藏div

时间:2014-11-26 08:36:45

标签: javascript jquery

让我们说有很多具有相同类别的div正在以链接的形式动态显示内容。我怎么能删除/隐藏那些包含诸如Sport,Television,Airline等词语的div?

e.g

<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>

4 个答案:

答案 0 :(得分:6)

你可以使用下面的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添加类名,用于多个

答案 1 :(得分:0)

$(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();
        }
    });
});

试试这个。

基本上我用calss迭代所有div并检查它们的内容是否具有你指定的字符串。如果是这样,我将其删除。

答案 2 :(得分:0)

我建议:

// 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>

参考文献:

答案 3 :(得分:0)

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