[英]Hide specific elements if another element contains a string with jQuery
我的网站上有一张优惠券轮播,我想实现以下功能:
对于每个优惠券,如果brandName包含文本“ test”,则隐藏包含它的div,这意味着我要隐藏所有在brandName上具有“ test”的优惠券。
因此,假设每个优惠券div如下:
<div class="coupon-box">
<div class="brandName">Test1</div>
<div class="coupon-image"><img src="coupon-image.jpg"></div>
</div>
我想隐藏他的标题上有“ test”字样的所有优惠券。 实际上,我已经设法完成了第一部分(获取具有文本的brandNames),但是我不知道如何隐藏其优惠券框。
到目前为止,我所做的是:
$( document ).ready(function() {
$('.brandName').each(function(){
var el= $(this);
var text = el.html();
if (text.indexOf("test") !==-1){
//missing-code
}
});
});
有什么建议么? 我尝试添加$('.coupon-box').css('display', 'none');
但是它只是隐藏了所有的优惠券
它不起作用,因为您正在选择所有元素,而不是当前所在的元素。因此,您需要查找该项的父元素。
所以选择元素的父元素
el.parent().hide();
或寻找与班级最亲近的祖先
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');
}
});
});
要小心,因为'test'!='Test'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.