my dynamic generated html look like below
<ul class="missingList">
<li>Please select at least one answer</li>
<li>Please select at least one answer</li>
<li>Please select at least one answer</li>
<li>Please select at least one answer</li>
<li>Please select at least one answer</li>
<li>Please select at least one answer2</li>
<li>Please select at least one answer2</li>
<li>Please select at least one ans开发者_JAVA技巧wer2</li>
</ul>
i want to use jquery to check for all duplication filter the result so that the output become
<ul class="missingList">
<li>Please select at least one answer</li>
<li>Please select at least one answer2</li>
</ul>
you can use something like a dictionary to keep track of the li`s html...
var obj ={};
$('.missingList').find('<li>').each(function)
{
$this = $(this);
if(obj[this.html()]
$this.parent().removeChild(this);
else
obj[$this.html()] = {}
});
$("li.missingList").each(function() {
var text = $(this).text();
if ($(this).prevAll().filter(function() { return $(this).text() == text; }).length > 0)
$(this).remove();
});
This is another way, which doesn't consider the order in which the items are traversed.
$('.missingList li').each(function() {
if(!$(this).next().length) return;
var currText = $(this).text();
$(this).nextAll().filter(function(){
return $(this).text() == currText;
}).remove();
});
Here's a worked out example.
I do agree that this should be handled on the server before going into JavaScript though.
Hi there the following JQuery/javascript function should do it. As it is a bit late at night I didnt get to test it or tidy it.
function RemoveDups() {
var $res = $("ul.missingList li");
$res.remove();
var i;
$res.sort(function(a, b) {
if ($(a).text() < $(b).text()) return -1;
if ($(a).text() == $(b).text()) return 0;
return 1;
});
lis=new Array();
lis.push($res[0]);
for (i = 1; i < $res.length; i++)
if($($res[i-1]).text()!=$($res[i]).text()) lis.push($res[i]);
$("ul.missingList").after(lis);
}
Try this:
$('.missingList li').each(function() {
if($(this).text() == $(this).next().text()) {
$(this).remove();
}
});
But if you are generating the list with PHP, it would be better to filter the result on its site, like bogdanvursu suggested.
Edit:
I think array_unique would be better for this. Here is an example
$array = array(1, 1, 1, 4, 5, 6);
$array = array_unique($array);
The result would look like this (1, 4, 5, 6)
How do you generate the LIs? In PHP you can use the array_filter function to filter the array.
精彩评论