【问题标题】:How can I use an anchor tag to submit a form with jquery如何使用锚标签提交带有 jquery 的表单
【发布时间】:2013-11-18 21:27:15
【问题描述】:

我想使用以下锚点将带有 jquery 的表单提交给 Spring。这是怎么做到的?

<a target="" title="" class="" href="">Save</a>

我试过了,requestNew 是我的表单:

 $(document).ready(function(){
  $("a").click(function(){
     $("#requestNew").submit(function(){
         $.post("../acctRequests", $("#requestNew").serialize());
      });
  });
 });

它似乎无处可去。

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    您正在添加一个新的事件处理程序;您需要做的就是触发现有的,以及浏览器的原生功能:

    $(document).ready(function(){
      $("a").click(function(){
         $("#requestNew").submit();
      });
    });
    

    【讨论】:

      【解决方案2】:

      请使用这个

      <a href="javascript:document.YOUR_FORM_NAME.submit()"> Submit</a>
      
      <form name="YOUR_FORM_NAME" action="YOUR_ACTION_PAGE_URL" method=POST>
                 <input type="text" name="YOUR_INPUT_NAME" value="YOUR_INPUT_VALUE"/>
            </form>
      

      将“YOUR_ACTION_PAGE_URL”替换为您的目标操作网址

      【讨论】:

        【解决方案3】:

        在点击之外分配提交处理程序。然后通过点击调用它。

        $(document).ready(function(){
               // Binds the submit handler to the #requestNew form
           $("#requestNew").submit(function(){
                $.post("../acctRequests", $("#requestNew").serialize());
           });
           $("a").click(function(e) {
                $("#requestNew").submit(); // calls the submit handler
                e.preventDefault();  // Prevents the default behavior of the link
           });
        });
        

        【讨论】:

        • 这是正确的方法。 lonesomeway 的答案(接受的答案)不适用于我的浏览器,因为锚标记的默认行为没有被覆盖,重新加载页面,同时随后丢失了发布数据。
        【解决方案4】:

        HTML

        <form...>
            ...
            <a data-role="submit">Save</a>
        </form>
        

        jQuery

        $(function(){
            $("[data-role=submit]").click(function(){
                $(this).closest("form").submit();
            });
        });
        

        【讨论】:

          【解决方案5】:

          如果您向锚点添加 id,您可以在 click 函数中提交表单:

          <a target="" title="" class="" href="" id="saveButton">Save</a>
          $(document).ready(function(){
            $('#saveButton').click(function(){
              $("#requestNew").submit(); //if requestNew is the id of your form
            });
          });
          

          如果您尝试使用 ajax 提交它,这是一个不同的解决方案,但根据您的问题,我不确定这是否是您想要的

          【讨论】:

            【解决方案6】:

            最简单的方法是这样的:

            <a href="#" onclick="submit()">Submit</a>
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2013-06-19
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-08-06
              相关资源
              最近更新 更多