问题描述:

I have the following JS file:

;(function ($) {

$('.filter-opts .opt').click(function(){

var selectedName = $(this).html();

$('.append').append('<li>' + selectedName + '</li>');

});

$(document).on('click', '.append li', function(){

$(this).remove();

});

})(jQuery);

Codepen: http://codepen.io/brunomonteiro3/pen/vGdJVR

As you can see, when a <li> option is clicked, it clone the element to another list. But I want to make sure if an item is already listed, it will not be listed again.

What would be the best option to verify it?

网友答案:

Check if the item already exists using filter funcition.

exist = $('.append li').filter(function() {
  return $(this).text() == selectedName
});
if (!exist.length)
  $('.append').append('<li>' + selectedName + '</li>');

DEMO

网友答案:

You should add a class or other identity attribute to each different item, and search for it:

$(function(){
    var $target = $(".append").first();
    $('.filter-opts .opt').click(function(){
        var name = $(this).attr("data-name");
        if ($target.find('[data-name="' + name + '"]').size() == 0) {
            $(this).clone().appendTo($target);
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="filter-opts">
  <li class="opt" data-name="o1">Option 1</li>
  <li class="opt" data-name="o2">Option 2</li>
  <li class="opt" data-name="o3">Option 3</li>
  <li class="opt" data-name="o4">Option 4</li>
</ul>

<h2>Appended:</h2>

<ul class="append">
</ul>
网友答案:

Here is one solution:

(function($) {
  var $secondList = $('.append');
  $('.filter-opts .opt').click(function() {
    var selectedName = $(this).text();
    if (!$secondList.find('li:contains("' + selectedName + '")').length) {
      $secondList.append('<li>' + selectedName + '</li>');
    }
  });

  $(document).on('click', '.append li', function() {
    $(this).remove();
  });
})(jQuery);

Codepen demo

相关阅读:
Top