Since jQuery 1.6, you can use .is
. Below is the answer from over a year ago...
var a = $('#foo');
var b = a;
if (a.is(b)) {
// the same object!
}
If you want to see if two variables are actually the same object, eg:
var a = $('#foo');
var b = a;
...then you can check their unique IDs. Every time you create a new jQuery object it gets an id.
if ($.data(a) == $.data(b)) {
// the same object!
}
Though, the same could be achieved with a simple a === b
, the above might at least show the next developer exactly what you're testing for.
In any case, that's probably not what you're after. If you wanted to check if two different jQuery objects contain the same set of elements, the you could use this:
$.fn.equals = function(compareTo) {
if (!compareTo || this.length != compareTo.length) {
return false;
}
for (var i = 0; i < this.length; ++i) {
if (this[i] !== compareTo[i]) {
return false;
}
}
return true;
};
Source
var a = $('p');
var b = $('p');
if (a.equals(b)) {
// same set
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…