我正在尝试制作ajax更新程序。现在我有div:
<ul class='topStatsOuter'>
<li class='liClass'>custom text</li>
<li class='liClass'>custom text two</li>
<li class='liClass'>custom text three</li>
</ul>
更新ul class:
success: function( result ) {
$( '.topStatsOuter' ).empty()
$.each( result.updatedtopics, function( id, topics )
{
$( '.topStatsOuter' ).append( topics.html );
});
}
如何比较原始div中未更新的内容与更新的div?
例如更新的div看起来像这样:
<ul class='topStatsOuter'>
<li class='liClass'>ajax added this li</li>
<li class='liClass'>custom text</li>
<li class='liClass'>custom text two</li>
<li class='liClass'>custom text three</li>
</ul>
我想要更改样式:更新后的背景,添加的li,( ajax添加此li )是否可能?看起来我想要在两个div之间得到区别。谢谢,抱歉我的英语不好。
EDIT。看起来这就是我想要的: http://jsfiddle.net/AzZHy/
答案 0 :(得分:0)
而不是清空ul
删除所有li
并保留其引用,稍后在追加时检查文本内容并提供样式。
success: function(result) {
// remove the element from ul and keep it's reference
var $li = $('.topStatsOuter li').detach();
$.each(result.updatedtopics, function(id, topics) {
// wrap html with jQuery, append it to ul and keep it's refernece
var $ele = $(topics.html).appendTo('.topStatsOuter');
// compare content with old elements, use filter for exact match
// or use `:contains()`, eg: if($li.filter(':contains(' + $ele.text().trim() + ')').length){ ... }
if ($li.filter(function() {
// check contents are the same after trimming the whitespace
return $(this).text().trim() == $ele.text().trim();
}).length)
// if old element with same content exist then update style
$ele.css('background', 'red')
});
}
var arr = ["<li class='liClass'>ajax added this li</li>",
"<li class='liClass'>custom text</li>",
"<li class='liClass'>custom text two</li>",
"<li class='liClass'>custom text three</li>"
];
var $li = $('.topStatsOuter li').remove();
$.each(arr, function(id, html) {
var $ele = $(html).appendTo('.topStatsOuter');
if ($li.filter(function() {
return $(this).text().trim() == $ele.text().trim();
}).length)
$ele.css('background', 'red')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class='topStatsOuter'>
<li class='liClass'>custom text</li>
<li class='liClass'>custom text two</li>
<li class='liClass'>custom text three</li>
</ul>