我有一个 ul
,它在 AJAX 请求后 append 了几个 li
。列表中先前的元素被删除,这是为什么?
AJAX调用函数:
var $comments = $('.comments').find('ul');
$comments.text('Loading...');
$.ajax({
type: 'get',
url: 'http://localhost/codeigniter/',
success: function(result){
if (result == 0){
$comments.text('No comments.');
return;
}
$comments.text('');
display_comments(result);
}
});
列表显示功能:
function display_comments(result){
var result_comments = JSON.parse(result);
var $ul = $('.comments').find('ul');
for (var i = 0; i < comments.length; i++){
// Insert comments
lis += '\
<li>\
' + comments[i].title + '\
<p>' + comments[i].description +'\
</li>';
}
$ul.append(lis);
}
最佳答案
因为这个
$comments.text('Loading...');
还有这个
$comments.text('No comments.');
还有这个
$comments.text('');
发生这种情况的原因是 jQuery 的 .text()
方法覆盖匹配元素的内容。在 ul
的情况下其内容是任意子 li
s。因此,当您开始加载列表项时,您的 ul
变为:<ul>Loading...</ul>
关于javascript - 使用 JQuery 追加元素会删除先前的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23798370/