【问题标题】:jQuery find next div within a parent of $thisjQuery 在 $this 的父级中找到下一个 div
【发布时间】:2015-12-13 13:33:37
【问题描述】:

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

【问题讨论】:

    标签: jquery parent next


    【解决方案1】:

    您需要获取“免费”容器的父节点(使用: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>
      

    【讨论】:

      【解决方案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/

      Ps:你的第一个div没有关闭,所以关闭吧。

      【讨论】:

      • 太棒了,谢谢。我还在学习(如你所知)。我走在正确的轨道上,但你的 cmets 教会了我我的方式的错误。再次感谢!
      【解决方案3】:

      条件是:

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

      并在里面使用这个:

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

      【讨论】:

        猜你喜欢
        • 2010-10-26
        • 2012-07-21
        • 2011-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多