jQuery为什么replaceWith只能运行一次?
问题描述:
我有一些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);
});
});
});
答
replaceWith()
不 “代替一个div数据” - 它实际上取代了元素,这意味着你将不能够选择它,因为.count
将在您的代码执行后消失。
相反,取代的.count
与html()
内HTML,这将是这样的:
$('.count').html(response);
表兄弟姐妹只有一个有'.count'?或者你的目标是所有的计数。 –
你的'response'包含一个'.count'类吗? – Dekel
那么......你正在更换.count--替换之后,没有那个类的元素了吧? – sinisake