我正在尝试清除LI标记以前的数据。
是否有另一个命令可以使用appendTo以外的其他命令?
以下是我的代码目前的样子:
var obj = JSON.parse(data);
$.each(obj, function(index, item)
{
$('<li>').
text(item.datestamp+' - '+item.comment).
appendTo($('#pCodeComment'));
});
不久前我问了一个类似的问题。我只是想知道是否有除appendTo之外的其他命令将清除以前的数据。
答案 0 :(得分:3)
你应该在循环填充之前清空列表,然后继续做你正在做的事情。
var obj = JSON.parse(data);
$('#pCodeComment').empty();
$.each(obj, function(index, item)
{
$('<li>').
text(item.datestamp+' - '+item.comment).
appendTo($('#pCodeComment'));
});
经过优化后:
var obj = JSON.parse(data); // i'm assuming `obj` is an array
var htmlToInsert = obj.map(function (item) {
return '<li>' + item.datestamp + ' - ' + item.comment + '</li>';
}).join('');
$('#pCodeComment').html(htmlToInsert);
注意:以上内容易受XSS攻击。有关解决问题的方法,请参阅this so question,或只使用原始文字。
答案 1 :(得分:0)
$.replaceWith()
可能是您正在寻找的,或者正如Kevin B指出的那样
$.html()
replaceWith需要选择要替换的元素。而html将填充父元素以插入新的dom片段。