jQuery 在 $this 的父元素中查找下一个 div

3
我在循环的div中遇到了一个问题,无法定位到特定的div。
我的代码是在页面上重复多次的单个项目。如果具有类名为edd_price的span内包含文本“Free”,我想隐藏仅此项目的div类名为'vat'的元素。
<div class="product-thumb">
  <a href="http://tb.eldo.co.uk/downloads/achieving-sales-on-the-telephone-sample-notes/">
  <div class="thum">
    <img width="185" height="150" src="blah"/>
  </div>
  <div class="title">Title goes here</div>
  <div class="price">
    <span class="edd_price">Free</span> 
  </div>
  <div class="vat clear">
    price excluding 20% vat                             
  </div>
</a>

我尝试过的所有方法要么没有任何影响,要么会影响页面上的所有项目。以下是我认为应该有效的方法:
$(document).ready(function() {
if ($(".edd_price").contains("Free")) {
  $(this).parent().next('div.vat').hide();
}
});
3个回答

2

首先,你的条件不起作用,contains方法应该是这样的:

if ( $(".edd_price:contains(free)"))

请看这里:http://www.w3schools.com/jquery/sel_contains.asp

如果您需要重新获取元素,因为您的this不是它。这不是一个回调函数。那么:

$(function() {
    if ( $(".edd_price:contains(free)")) {
        $('.edd_price:contains("Free")').parent().next('.vat').hide();
    }
});

这是演示: https://jsfiddle.net/87qcfng8/ 提示:你的第一个div没有关闭,请关闭它。

2
太棒了,谢谢。我还在学习中(正如你所看到的)。我走在正确的道路上,但是你的评论让我认识到了我的错误。再次感谢! - Scott Eldo

1

条件是:

if ( $(".edd_price:contains(free)"))

使用此内容:

并嵌入:

$('.edd_price:contains("Free")').parent().next('.vat').hide();

0
你需要获取“Free”容器的父节点(使用:contains("Free")选择器检索),并隐藏具有类.vat的下一个元素:
$('.edd_price:contains("Free")').parent().next('.vat').hide();

这里有一个演示:

$('.edd_price:contains("Free")').parent().next('.vat').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="product-thumb"> 
  <a href="http://tb.eldo.co.uk/downloads/achieving-sales-on-the-telephone-sample-notes/">
  <div class="thum">
    <img width="185" height="150" src="http://lorempixel.com/185/150"/>
  </div>
  <div class="title">Title goes here</div>
  <div class="price">
    <span class="edd_price">Free</span> 
  </div>
  <div class="vat clear">
    price excluding 20% vat                             
  </div>
</a>
  


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接