我每5秒调用一次服务器来获取数据,然后遍历我的列表并将带有正确数据的“span”附加到我的列表中。问题是,当从服务器返回的数据为空时,我无法使“span”消失,除非我在“span”上使用“fadeOut()”。但是我无法计算所有“li span”(countCont())的正确总和,因为它们仍然附加到DOM并具有值。 所以我想要做的是删除相应的“li span”,如果从分配给它的服务器返回的数据是空的,那么我可以计算正确的总和。 以下是我如何将数据分配到我的列表:
$.get(url, function (data) {
$.each(data, function (i, info) {
$("#accordion li").text(function (y, name) {
if ($(this).is(":contains(" + info.cName + ")")) {
if ($(this).is(":has(span)")) {
$(this).children().replaceWith('<span class = "cCount">' + info.count + '</span>');
$(this).children().fadeOut(10000);
} else {
$(this).append('<span class = "cCount">' + info.count + '</span>');
}
}
countCont($(this).parent().attr('id'));
});
});
});
答案 0 :(得分:0)
淡出后,使用.remove()
将其从DOM中删除//...
$("#accordion li").text(function (y, name) {
var $this = $(this); //also store this, dont select it 5 times
if ($this.is(":contains(" + info.cName + ")")) {
if ($this.is(":has(span)")) {
$this.children().replaceWith('<span class = "cCount">' + info.count + '</span>');
$this.children().fadeOut(10000);
$this.remove();
} else {
$this.append('<span class = "cCount">' + info.count + '</span>');
}
}
countCont($this.parent().attr('id'));
});
修改:在回复评论时,如果该评论存在,则会删除该字距,然后添加新评论:
//...
var $this = $(this); //also store this, dont select it 5 times
if ($this.is(":contains(" + info.cName + ")")) {
if ($this.is(":has(span)")) {
//remove the span
var $span = $('span', this);
$span.fadeOut(10000);
$span.remove();
}
//always append new span
$this.append('<span class = "cCount">' + info.count + '</span>');
}