【问题标题】:Make a tag act like input button使标签像输入按钮一样
【发布时间】:2012-01-26 19:41:57
【问题描述】:

如何使<a href="http://test/com/tag/test">Test</a> 像表单按钮一样工作?通过像表单按钮一样操作,我的意思是当单击链接以执行 method="get" 或发布时,以便能够通过获取或发布来捕获它。

不一定非得是一个链接,我可以适应以使它像那样工作!

【问题讨论】:

    标签: javascript jquery post get hyperlink


    【解决方案1】:

    如果您想使用链接提交表单:

    HTML --

    <form action="my-page.php" id="my-form" method="post">...</form>
    <a href="#" id="form-submit">SUBMIT</a>
    

    JS--

    $(function () {
        $('#form-submit').on('click', function () {
    
            //fire the submit event on the form
            $('#my-form').trigger('submit');
    
            //stop the default behavior of the link
            return false;
        });
    });
    

    trigger() 的文档:http://api.jquery.com/trigger

    如果您想在不离开页面的情况下提交表单,可以使用 AJAX 调用:

    $(function () {
        $('#form-submit').on('click', function () {
    
            //cache the form element for use later
            var $form = $('#my-form');
            $.ajax({
                url     : $form.attr('action') || '',//set the action of the AJAX request
                type    : $form.attr('method') || 'get',//set the method of the AJAX reqeuest
                data    : $form.serialize(),
                success : function (serverResponse) {
    
                    //you can do what you want now, the form has been submitted, and you have received the serverResponse
                    alert('Form Submitted!');
                }
            });
        });
    
        $('#my-form').on('submit', function () {
    
            //stop the normal submission of the form, for instance if someone presses the enter key inside a text input
            return false;
        });
    });
    

    $.ajax() 的文档:http://api.jquery.com/jquery.ajax

    请注意,.on() 是 jQuery 1.7 中的新功能,在这种情况下与使用 .bind() 相同。

    【讨论】:

    • Frankie 的解决方案使用 AJAX...$.get() 函数与$.ajax({type:'get'}) 是一回事。我刚刚更新了我的$.ajax 代码以包含表单的数据,这可能非常重要:)
    【解决方案2】:
    <form ....>
        <a id="whatever" href="http://test/com/tag/test">Test</a>
    </form>
    

    假设您的表单中有任何带有 ID 的元素,您可以使用 jQuery 选择该 ID 并在其上附加一个 click 事件。在这种特殊情况下,它还将使用get/whatever.php 请求数据,您应该对其进行微调以同时使用get/post 并根据您的需要序列化表单数据。

    $("#whatever").click(function(){
      $.get("/whatever.php");
    });
    

    【讨论】:

    • 一定要设置&lt;form...&gt;吗?
    • @w0rldart,不...不用表格也可以。
    • 如果您想在请求中包含表单中的数据,那么您可以在$.get() 函数中添加$('form').serialize() 作为第二个参数:api.jquery.com/serialize
    • 是我写错了还是$.get() 没有刷新页面?
    • 我需要刷新页面,因为当将 a 的数据发送到获取数据的控制器时,它将自动建立一个链接
    【解决方案3】:

    没有 jQuery

    <form id="your_form">
        <a href="javascript:{}" onclick="document.getElementById('your_form').submit(); return false;">submit</a>
    </form>
    

    【讨论】:

      猜你喜欢
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      • 2013-04-14
      • 2012-10-17
      • 1970-01-01
      • 2013-05-16
      • 2011-08-07
      • 1970-01-01
      相关资源
      最近更新 更多