我正在編寫一個模塊,該模塊有多個用戶可以選擇回答的問題。每個人都有自己的提交按鈕,導致數據被髮布到我的應用程序,顯示結果,然後刪除表單。我能夠很好地完成這個工作,但如果我添加一個允許用戶一次提交所有表單的按鈕,它會正確提交表單數據,但結果會附加到最後一個問題(這些項目正在獲取正確的數據) 。這是JavaScript/jQuery的代碼,我使用的是:保持一致的值在jQuery中同時運行多個項目時功能
// setup the save answer click handler
$(document).on('click', '.saveAnswer', function(event){
event.preventDefault();
// get the form
form = $(this).closest('form');
$.ajax({
async:true,
type: 'POST',
url: form.attr('action'),
data: form.serialize(),
success: function(data){
// append the text to the bottom of the answers
form.closest('.question').find('.answers').append('<li>' + data + '</li>').hide().slideDown(500);
form.slideUp(500,function(){
form.remove();
});
}
});
});
// setup the save all answer click handler
$(document).on('click', '.saveAll', function(){
$('.saveAnswer').trigger('click');
});
如果我的async
值更改爲false,然後它工作正常,但沒有一個動畫的工作,並在頁面似乎凍結第二個,直到所有的答案已提交。
經過一番調試,我發現form
變量每次運行該函數都會被覆蓋。有沒有辦法來防止這種情況發生?
'form'是一個全球性的(或至少是高範圍)變量。使它成爲本地('var form = $(....);')。 – DCoder
@DCoder感謝您的快速響應。將其添加爲答案,我將接受它。 –