jQuery compare two DOM object?

三世轮回 提交于 2020-01-09 10:25:12

问题


Clicking on an element:

$('.my_list').click(function(){
   var selected_object = $(this);

   $('.my_list').each(function(){
      var current_object = $(this);

      if( selected_object == current_object ) alert('FOUND IT !');
   });
});

I don't know why, but I don't get the alert message "FOUND IT !".


回答1:


You can use the jQuery.is function:

Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

if (selected_object.is(current_object)) {
   ...    
}

An alternate solution is to use jQuery.get function to get the raw elements and compare them using == or === operator:

if (selected_object.get(0) == current_object.get(0)) {
   ...
}

jsFiddle demo




回答2:


There's good answer provided... but it's important to understand, why you directly can't compare selectors in jQuery.

jQuery selectors return data structures which will never be equal in the sense of reference equality. So the only way to figure this out is to get DOM reference from the jQuery object and to compare DOM elements.

The simplest comparison of DOM reference for the above example would be:

selected_object.[0] == current_object.[0]


来源:https://stackoverflow.com/questions/15197477/jquery-compare-two-dom-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!