繁体   English   中英

jQuery检查span类并隐藏最接近的div

[英]jQuery check span class and hide closest div

我很难弄清楚为什么这个功能不能正常工作。 我尝试使用.html val trim ! :contains' '.text和其他变体,以使用特定类测试跨度内的字符串,但控制台似乎可以正确返回对象,但是失败。 任何帮助表示赞赏。

 if (jQuery('.price').text() == '') { jQuery(this).closest(".box").hide(); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="box"> test content<br> <span class="price">$99.99</span> </div> <div class="box"> test content<br> <span class="price">$99.99</span> </div> <div class="box"> test content<br> <span class="price"></span> </div> <div class="box"> test content<br> <span class="price"></span> </div> <div class="box"> test content<br> <span class="price">$99.99</span> </div> 

代码的问题是因为您要一次从所有 .price元素中检索text() 相反,您需要遍历它们并单独检查文本,然后隐藏相关的.box ,如下所示:

 $('.price').each(function() { if ($(this).text().trim() == '') { $(this).closest('.box').hide(); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="box"> test content <br> <span class="price">$99.99</span> </div> <div class="box"> test content <br> <span class="price">$99.99</span> </div> <div class="box"> test content <br> <span class="price"></span> </div> <div class="box"> test content <br> <span class="price"></span> </div> <div class="box"> test content <br> <span class="price">$99.99</span> </div> 

您需要循环真实每个元素。

$('.price').each( function(index) {
  if ($(this).text() == "") {
    $(this).closest(".box").hide();
  }
});

但是您的HTML存在问题。 因为.box类有2个近邻

我没有得到您的确切要求。 尝试以下代码可能会对您有所帮助。

if (jQuery('.price').text() != '') {
  jQuery('.price').closest(".box").hide();
}

暂无
暂无

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

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