jQuery($(this).parent()发现不起作用

时间:2018-03-01 14:21:52

标签: javascript jquery

我似乎无法让jquery找到我所拥有的产品网格。知道如何设置它吗?

<div id="sold-out" style="margin-top: 10px">
  <a class="grid-view-item__link grid-view-item__image-container" href=
  "/products/moringa-and-coconut-soap"></a>
  <form accept-charset="UTF-8" action="/contact#contact_form" class=
  "contact-form" id="contact_form" method="post" name="contact_form">
    <a class="grid-view-item__link grid-view-item__image-container" href=
    "/products/moringa-and-coconut-soap"><input name="form_type" type="hidden"
    value="contact"><input name="utf8" type="hidden" value="✓"></a>
    <p><a class="grid-view-item__link grid-view-item__image-container" href=
    "/products/moringa-and-coconut-soap"></a><a class=
    "product-page-notify-me notify-me" href="#" style="color: #788188;">Email
    me when available</a></p>
    <div class="clearfix notify-me-wrapper" style="display:none">
      <input class="styled-input" name="contact[email]" placeholder=
      "your@email.com" required="required" style="float:left; width:100%;"
      type="email" value=""> <input name="contact[body]" type="hidden" value=
      "Please notify me when Moringa and Coconut Soap becomes available.">
      <input class="btn styled-submit" style="float:left;" type="submit" value=
      "Send">
    </div>
  </form>
</div>

Javascript代码:

jQuery('.notify-me').click(function() {
  alert('hello');
  jQuery($(this).parent().find('.notify-me-wrapper').fadeIn());           
  return false;
});

然而,我的另一页上的代码针对一个项目,工作正常:

jQuery('#notify-me').click(function() {

jQuery('#notify-me-wrapper').fadeIn();           

return false;
} );

2 个答案:

答案 0 :(得分:6)

.notify-me的父级是p元素,此元素不包含任何具有calss notify-me-wrapper的后代

您可能希望使用closest,这样您就可以搜索您确定其中包含类notify-me-wrapper的元素的最近祖先:

$(this).closest('.contact-form').find('.notify-me-wrapper').fadeIn()

jQuery.closest()

  

对于集合中的每个元素,通过测试元素本身并遍历DOM树中的祖先来获取与选择器匹配的第一个元素。

答案 1 :(得分:1)

.notify-me的父级是p标记(段落),您要查找的元素是下一个兄弟。因此,改变:

jQuery($(this).parent().find('.notify-me-wrapper').fadeIn());    

使用:

jQuery($(this).parent().next('.notify-me-wrapper').fadeIn());

使用.find()更改.next()