jquery remove duplicate li

后端 未结 5 1770
青春惊慌失措
青春惊慌失措 2020-12-05 16:06
  • microsoft
  • microsoft
  • apple
  • apple
相关标签:
5条回答
  • 2020-12-05 16:27
    uniqueLi = {};
    
    $("#myid li").each(function () {
      var thisVal = $(this).text();
    
      if ( !(thisVal in uniqueLi) ) {
        uniqueLi[thisVal] = "";
      } else {
        $(this).remove();
      }
    })
    

    This build an index (an object) of unique values. For your example, uniqueLi will look like this afterwards:

    {
      "microsoft": "", 
      "apple": ""
    }
    

    So whenever a value is encountered that has been added to the index before, the associated <li> gets removed.

    0 讨论(0)
  • 2020-12-05 16:29

    Here's a function that will do it, a slightly different way:

    function removeDuplicateItems(id) {
        var ul = $('#' + id);
    
        $('li', ul).each(function() {
            if($('li:contains("' + $(this).text() + '")', ul).length > 1)
                $(this).remove();
        });
    }
    

    Call with removeDuplicateItems('myid');

    0 讨论(0)
  • 2020-12-05 16:34

    You could use

    var inner = [];
    $('li').each( function(index, Element){
        if (jQuery.inArray(this.innerHTML, inner) == -1){
          inner.push(this.innerHTML);
        }
        else {
          $(this).remove();
        }
    });
    
    0 讨论(0)
  • 2020-12-05 16:42

    I have used @Thariama solution in the past, but I have compatibility problems with IE6 (I still needs to support this dinosaur).

    If the item repeats, so remove it from ul. It works with dynamic added li.

                var seen = {};
                $("ul#emails_exclusion_list").find("li").each(function(index, html_obj) {
                    txt = $(this).text().toLowerCase();
    
                    if(seen[txt]) {
                        $(this).remove();
                    } else {
                        seen[txt] = true;
                    }
                });
    
    0 讨论(0)
  • 2020-12-05 16:44

    example I find that the script is faster

    var liText = '', liList = $('#myid li'), listForRemove = [];
    
    $(liList).each(function () {
    
      var text = $(this).text();
    
      if (liText.indexOf('|'+ text + '|') == -1)
        liText += '|'+ text + '|';
      else
        listForRemove.push($(this));
    
    })​;
    
    $(listForRemove).each(function () { $(this).remove(); });
    
    0 讨论(0)
提交回复
热议问题