![](/img/trans.png)
[英]jQuery compare two sets of objects and get the location of the difference in the value
[英]Jquery compare two divs, get difference
我正在嘗試制作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添加了此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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.