2017-06-17 65 views
2

我有一個問題。我認爲這是因爲渲染,但我不知道,因爲這個話題對我來說是新的。JavaScript提交按鈕jQuery問題

好吧,我有一個簡單的表格:

<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... 
     }  
    }); 
}); 

還行,代碼工作真的很好。它做它應該做的事情。但是,如果我想發送第二個請求,則提交按鈕不能按預期工作。它試圖使用默認操作發送表單,儘管我預先設定了這一點 - 至少這就是我的想法。

我確實使用谷歌,但我甚至不知道如何解釋我的問題。

希望有人能幫助我,非常感謝!

格爾茨

+2

提交事件應的形式,而不是按鈕上放。這也有幫助,因爲表單元素本身沒有變化,因此事件監聽器保持原位 –

回答

2

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

.clone(true):創建匹配的元素的深層副本。

.replaceWith():用提供的新內容替換匹配元素集合中的每個元素,並返回被刪除的元素集合。

事件必須點擊如果連接到提交按鈕或提交如果附着的形式。

的片段:

$('[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>

+0

非常感謝你,你的代碼解決了我的問題問題。 – PaddaelsM

0

使用$(document).on("click", "[type=submit]", function (e) {動態創建ekements代替$('[type=submit]').submit(function(e) {

0

使用<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... 
     }  
    }); 
} 

我希望能解決你的問題。

+0

對不起,但我應該補充說,調用函數並沒有解決我的問題:/ – PaddaelsM