简体   繁体   English

在表单外部调用此函数

[英]Call This Function Outside of Form Submit

I have a submit button at the end of my form that is labeled like this: 我在表单的末尾有一个提交按钮,其标签如下:

<button id="sendbutton" style="margin-left:25px;" class="btn btn-large btn-primary" type="submit">Send Responses</button>

This button calls this script: 此按钮调用此脚本:

<script type="text/javascript">
        $(function() {
            $('form').unbind('submit').bind('submit', function(){
                $.ajax({
                    type: 'post',
                    url: 'chapter.php',
                    data: $("form").serialize(),
                    success: function() {
                        alert('Your answers have been saved.');
                    }
                });
                return false;
            });
        });

    </script>

How do I create a button outside of this form structure that will call the same function? 如何在此表单结构之外创建一个将调用相同功能的按钮?

You can write a click handler to the new button and in the handler trigger the form submit using script 您可以将点击处理程序写入新按钮,然后在处理程序中使用脚本触发表单提交

<button id="test" style="margin-left:25px;" class="btn btn-large btn-primary" type="button">Send Responses</button>

then 然后

jQuery(function($){
    $('#test').click(function(){
        $('form').submit()
    })
})

You may create whatever button you'd like, even if its outside of the form. 您可以创建任何想要的按钮,即使该按钮不在表单中。 And then, to get that button to do the same thing you could simply do 然后,要使该按钮执行相同的操作,您可以简单地执行

$('#yourNewButton').click(function(){
    $('form').submit();
});

Or, why not wrap up your original logic into its own function 或者,为什么不将原始逻辑包装成自己的函数

function submitMyForm(){
    $.ajax({
        type: 'post',
        url: 'chapter.php',
        data: $("form").serialize(),
        success: function() {
            alert('Your answers have been saved.');
        }
    });
    return false;
 }

And then 接着

$('#yourNewButton').click(submitMyForm);
$('form').submit(submitMyForm);

Rather than make the submit handler an anonymous function you make it a named function 与其将提交处理程序设为匿名函数,不如将其命名为函数

function submitHandler() {
    $.ajax({
        type: 'post',
        url: 'chapter.php',
        data: $("form").serialize(),
        success: function () {
            alert('Your answers have been saved.');
        }
    });
    return false;
}

then change your code to 然后将您的代码更改为

$('form').unbind('submit').bind('submit', submitHandler);

That way you can call that function whenever you like simple by writing submitHandler(); 这样,您可以通过编写submitHandler();随时调用该函数submitHandler();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM