使标签充当输入按钮

2024-05-12

我怎样才能做一个<a href="http://test/com/tag/test">Test</a>就像表单按钮一样?通过充当表单按钮,我的意思是,当单击链接执行操作时method="get"或 post 以便能够通过 get 或 post 捕获它。

不一定是链接,我可以调整以使其像那样工作!


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

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 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 http://api.jquery.com/jquery.ajax

注意.on()是 jQuery 1.7 中的新功能,在本例中与使用相同.bind().

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使标签充当输入按钮 的相关文章

随机推荐