2017-01-02 54 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);