我正在尝试制作 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 类:
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 added this li)这可能吗?看起来我想区分两个 div。谢谢,抱歉我的英语不好。
编辑。看起来这就是我想要的: http://jsfiddle.net/AzZHy/
最佳答案
不是清空 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>
关于javascript - jquery比较两个div,得到差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41912281/