简体   繁体   中英

how to check if a ul has a particular li with jQuery?

I am working on the two ul lists. What I need is if someone click on the list item in list1, it will check if the 2nd list contains the clicked element or not. If it does not contain the element then copy it else just return.

What I have done so far is I am moving the elements successfully between the list but if I apply a check on it everything stops working.

Here is the link of jsfiddle .

$().ready(function() {
  var classHighlight = 'highlight';
  var $thumbs = $('ul li').on("click", function(e) {
    //e.preventDefault();
    debugger;
    $thumbs.removeClass(classHighlight);
    $(this).addClass(classHighlight);
  });
  $('#select1').on("dblclick", "li", function() {
    //if($("#select2").has($(this))
        //return;
    //else
        $(this).clone().appendTo('#select2').removeClass('highlight');
  });
  $('#select2').on("dblclick", "li", function() {
    $(this).remove();
  });
  $('#add').click(function() {
    $('#select1.highlight').clone().appendTo('#select2').removeClass(classHighlight);
  });
  $('#remove').click(function() {
    $('#select2.highlight').remove();
  });
});

If you un comment the above lines in code everything stop working. Can any one please help me with this?

Thanks

Try this check:

var check = function(li) {
    return $("#select2 li").filter(function(i, li2) {
        return $(li2).text() == $(li).text();
    }).length > 0;
};

Demo

As you're using clone() , you can't compare the new cloned element using is() or has() with the orignal one, because it is a new element, it isn't the same, as stated in clone 's docs:

Create a deep copy of the set of matched elements

So it's a copy.

You have a missing paren.

This if($("#select2").has($(this)) should be this if($("#select2").has($(this))) .

Also you can just pass this: if($("#select2").has(this))

And you have to check length: if($("#select2").has(this).length)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM