如何在使用jQuery单击元素时查找父表单元素?

时间:2018-04-18 09:16:12

标签: javascript jquery html

当我点击立即订购按钮(<a class="btn btn-lp btn-popup" data-popup-open="popup-1" href="#">Order Now</a>)时,会出现一个弹出窗口,其中包含将数据发送到服务器的表单按钮。

<div class="section-pick-your-box section-choose-a-plan">
  <ul class="content">
    <li>
      <div class="wrapper">
        <a class="btn btn-lp btn-popup" data-popup-open="popup-1" href="#">Order Now</a>
        <div class="popup" data-popup="popup-1">
          <div class="popup-inner">
            <form action="/cart/add" method="post" novalidate enctype="multipart/form-data" data-productid="">
              <input type="hidden" name="properties[shipping_interval_frequency]" value="1">
              <input type="hidden" name="properties[shipping_interval_unit_type]" value="Months">
              <input type="hidden" name="id" value="12673316716586">
              <input type="hidden" name="properties[subscription_id]" value="106203">
              <input type="hidden" name="purchase_type" value="autodeliver">

              <div class="price-button-wrap">
                <a class="btn btn-lp buy-now" href="/cart">Wrapped</a>
              </div>
            </form>
            <form action="/cart/add" method="post" novalidate enctype="multipart/form-data" data-productid="">
              <input type="hidden" name="properties[shipping_interval_frequency]" value="1">
              <input type="hidden" name="properties[shipping_interval_unit_type]" value="Months">
              <input type="hidden" name="id" value="12673316683818">
              <input type="hidden" name="properties[subscription_id]" value="106203">
              <input type="hidden" name="purchase_type" value="autodeliver">

              <div class="price-button-wrap">
                <a class="btn btn-lp buy-now" href="/cart">Unwrapped</a>
              </div>
            </form>
            <p><a data-popup-close="popup-1" href="#">Close</a></p>
            <a class="popup-close" data-popup-close="popup-1" href="#">x</a>
          </div>
        </div>
      </div>
    </li>
  </ul>
</div>

上面代码的问题在于它无法识别触发按钮的父窗体或最近的窗体元素。

这是我当前的jquery代码,用于获取父表单元素:

$('.section-pick-your-box .content > li .popup-inner > form .buy-now').click(function(e) {
  e.preventDefault();
  var $data = $(this).closest('li').find('form').serialize();
  console.log($data);
});

当我console.log时,我会收到两种表格的数据。

感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

由于form内有多个li,因此请检查最近的li

,而不是最近的form
 var $data = $(this).closest('form').serialize();