2017-01-02 101 views
1

我有一些jQuery代碼,每次提交表單時都會替換div中的數據。由於某種原因,replaceWith函數只能代替div一次?誰能告訴我我錯過了什麼?jQuery爲什麼replaceWith只能運行一次?

HTML

<div class="count"></div> 

jQuery的

$(document).ready(function(){ 
    $("#like_unlike").submit(function(e) { //Second Form 
    e.preventDefault(); 
    var url = "update_likes.php"; //Grab URL from form 
    var formdata = $(this).serialize(); 
    console.log(formdata); 
    $.post(url, formdata, function(response) { 
     //Post the form 
     $('.count').replaceWith(response); 
    }); 
    }); 
}); 
+0

表兄弟姐妹只有一個有'.count'?或者你的目標是所有的計數。 –

+2

你的'response'包含一個'.count'類嗎? – Dekel

+1

那麼......你正在更換.count--替換之後,沒有那個類的元素了吧? – sinisake

回答

5

replaceWith()不 「代替一個div數據」 - 它實際上取代了元素,這意味着你將不能夠選擇它,因爲.count將在您的代碼執行後消失。

相反,取代的.counthtml()內HTML,這將是這樣的:

$('.count').html(response);