JavaScript jQuery 提交按钮问题

JavaScript jQuery issue with submit button

我有问题。我认为这是因为渲染但我不知道,因为那个话题对我来说是新的。

好的,我有一个简单的表格:

<form method="post" action="/send-mail">
<input type="text" name="msg" value="">
<input type="submit" value="send that fancy mail">
</form>

现在我想使用 jQuery 捕捉提交,例如:

$('[type=submit]').submit(function(e) {
    e.preventDefault();
    var formHtml = $(this).parent().html();

    $.ajax({
        ..all these options..,
        beforeSend: function(xhr) {
            $('form').html("sending mail");
        },
        success: function(data) {
            $('form').html(formHtml); // I think here's the problem...
        }     
    });
});

好的,该代码工作得很好。它做了它应该做的。但是,如果我想发送第二个请求,提交按钮将不再按预期工作。它尝试使用默认操作发送表单,尽管我阻止了 - 至少我是这么想的。

我确实使用了google,但我什至不知道如何解释我的问题。

希望有人能帮助我,非常感谢!

问候

对动态创建的元素使用 $(document).on("click", "[type=submit]", function (e) { 而不是 $('[type=submit]').submit(function(e) {

使用 <input type="button"> 而不是 <input type="submit"> 并添加一个 onclick 函数,如下所示:

<input type="button" onclick="_submitForm()" value="send that fancy mail">

然后你的js将是:

function _submitForm(){
var formHtml = $(this).parent().html();

    $.ajax({
        ..all these options..,
        beforeSend: function(xhr) {
            $('form').html("sending mail");
        },
        success: function(data) {
            $('form').html(formHtml); // I think here's the problem...
        }     
    });
}

希望能解决您的问题。

而不是 .html() 你可以使用:

.clone(true): Create a deep copy of the set of matched elements.

.replaceWith(): Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.

事件必须是 click 如果附加到提交按钮或 submit 如果附加到表单。

片段:

$('[type=submit]').on('click', function (e) {
    e.preventDefault();
    var formHtml = $(this).closest('form').clone(true);
    $.ajax({
        dataType: "json",
        url: 'https://api.github.com/repos/octocat/Hello-World',
        beforeSend: function (xhr) {
            $('form').html("sending mail");
        },
        success: function (data) {
            console.log('Success');
            $('form').replaceWith(formHtml); // I think here's the problem...
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<form method="post" action="/send-mail">
    <input type="text" name="msg" value="">
    <input type="submit" value="send that fancy mail">
</form>