【问题标题】:in jquery, how can i reference current form from button click在 jquery 中,如何通过单击按钮引用当前表单
【发布时间】:2011-08-22 13:39:59
【问题描述】:

我在下面有一个表格;我已将提交按钮更改为只输入“按钮”,这样我就可以在提交表单之前运行一些 JavaScript:

这是我的表格:

<form action="/Cart" method="post">
     <input type="hidden" name="name" value="12" />
     <input type="button" class="addToCartButton" value="Add to Cart" />
 </form>

这是我的初始事件处理程序:

$(document).ready(function () {
    $('.addToCartButton').click(function () {

       //need to reference current form here
       //need to reference the hidden input with name="Name" above
    });
});

我在同一页面上有许多这样的表单,所以我需要相对引用表单和该表单内的一些其他输入。最好的方法是什么?我正在考虑为每个表单添加一些唯一的前缀,然后在选择器中使用它,但这看起来很hacky ...

【问题讨论】:

    标签: jquery html forms


    【解决方案1】:

    这应该可行:

    $(document).ready(function () {
        $('.addToCartButton').click(function () {
    
           //need to reference current form here
           $(this).closest('form');
           //need to reference the hidden input with name="Name" above
           $(this).closest('form').find('input[name="name"]');
        });
    });
    

    【讨论】:

      【解决方案2】:

      jQuery 最接近的() 将沿着树向上移动并返回与选择器匹配的第一个元素:

      $(this).closest("form");
      

      【讨论】:

      • htanks 快速响应。引用表单中的其他隐藏字段怎么样,(现在您有了引用)
      • 正如其他人指出的那样,您可以使用 find('input[name="name"]') 尽管您可能希望使用比名称更具描述性的值,可能是 formName?
      【解决方案3】:
       $(this).siblings("input[name='name']"); // the field
       $(this).closest("form");  // the form
      

      【讨论】:

        【解决方案4】:
         $('.addToCartButton').click(function () {
        
               //need to reference current form here
               var the_form = $(this).closest("form");
        
               //need to reference the hidden input with name="Name" above
               var the_input = the_form.find('input[name="name"]');
          });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-03-18
          • 2011-05-22
          • 2019-07-20
          • 2012-11-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多