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

标签 javascript jquery

我似乎无法让 jquery find 在我拥有的产品网格上工作。知道如何设置吗?

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

最佳答案

.notify-me 的父元素是 p 元素,并且该元素不包含任何带有 notify-me-wrapper 类的后代元素>

您可能想使用closest ,这样您就可以搜索最接近的祖先,您确定它包含具有类 notify-me-wrapper 的元素:

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

jQuery.closest() :

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

关于javascript - jQuery($(this).parent() 发现不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49051728/

相关文章:

javascript - 使用点击处理程序 (JS) 隐藏和显示 div 在 Firefox 中不起作用

javascript - 警报消息不起作用后重定向

javascript - 添加单选按钮的值

php - 许多许多 css 背景性能

javascript - 语法错误 : Failed to execute 'querySelector' on 'Document' : '[object HTMLDocument]' is not a valid selector

javascript - 达到10行后如何触发DataTables中的下一个按钮

jQuery,点击事件后中断或重置

javascript - 除了问号之外还有其他缓存方法吗?

javascript - IFrame 中不会发生事件冒泡

javascript - 如何将表导出为 10000 到 40000 行的 excel