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

ih99xse1  于 2023-06-22  发布在  jQuery
关注(0)|答案(3)|浏览(184)

我在一个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();
}
});
0g0grzrc

0g0grzrc1#

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

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

看看这里:http://www.w3schools.com/jquery/sel_contains.asp
在这种情况下,你必须再次得到元素,因为你的这个不是他。这不是回调。然后:

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

下面是演示:https://jsfiddle.net/87qcfng8/
Ps:你的第一个div没有关闭,所以关闭它。

qncylg1j

qncylg1j2#

条件是:

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

在里面使用这个:

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

olhwl3o23#

你需要获取“Free”容器的父节点(使用:contains("Free")选择器检索),并使用类.vat隐藏下一个元素:

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

下面是一个demo:

$('.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>

相关问题