问题
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