简体   繁体   English

如果另一个元素包含带有jQuery的字符串,则隐藏特定元素

[英]Hide specific elements if another element contains a string with jQuery

I have a carousel of coupons at my site and I want to achieve the following functionality: 我的网站上有一张优惠券轮播,我想实现以下功能:
For each coupon, if the brandName contains the text 'test' then hide the div that contains it which means that I want to hide all the coupons that have 'test' at their brandName. 对于每个优惠券,如果brandName包含文本“ test”,则隐藏包含它的div,这意味着我要隐藏所有在brandName上具有“ test”的优惠券。
So, suppose that the each coupons div is the following: 因此,假设每个优惠券div如下:

<div class="coupon-box">
  <div class="brandName">Test1</div>
  <div class="coupon-image"><img src="coupon-image.jpg"></div>
</div>

I want to hide every coupon that has 'test' at his title. 我想隐藏他的标题上有“ test”字样的所有优惠券。 I have actually managed to do the first part(getting the brandNames that have the text) but I don't know how to hide its coupon box. 实际上,我已经设法完成了第一部分(获取具有文本的brandNames),但是我不知道如何隐藏其优惠券框。
What I've done until now is the following: 到目前为止,我所做的是:

$( document ).ready(function() {
    $('.brandName').each(function(){
       var el= $(this);
       var text = el.html();
       if (text.indexOf("test") !==-1){
          //missing-code
       }
   });
});

Any suggestions? 有什么建议么? I tried adding $('.coupon-box').css('display', 'none'); 我尝试添加$('.coupon-box').css('display', 'none'); but it just hides all coupons 但是它只是隐藏了所有的优惠券

It does not work because you are selecting all the elements and not the one you are currently in. So you need to look for the parent element of the item. 它不起作用,因为您正在选择所有元素,而不是当前所在的元素。因此,您需要查找该项的父元素。

So select the parent of the element 所以选择元素的父元素

el.parent().hide();

or look for the closest ancestor with the class 或寻找与班级最亲近的祖先

el.closest(".coupon-box").hide();
$( document ).ready(function() {
    $('.brandName').each(function(){
       var el= $(this);
       var text = el.html();
       if (text.indexOf("test") !==-1){
         el.parent().css('display', 'none');
       }
   });
});

Be careful, because 'test' != 'Test' 要小心,因为'test'!='Test'

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

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