如何比较 jQuery 对象?

所以我试图找出如何比较两个 jQuery 对象,看看父元素是否是页面的主体。

这是我的发现:

if ( $(this).parent() === $('body') ) ...

我知道这么做不对,但如果有人明白我的意思,他们能告诉我正确的做法吗?

78563 次浏览

You need to compare the raw DOM elements, e.g.:

if ($(this).parent().get(0) === $('body').get(0))

or

if ($(this).parent()[0] === $('body')[0])

Why not:

if ($(this).parent().is("body")) {
...
}

?

Looping is not required, testing the single first node is not required. Pretty much nothing is required other than ensuring they are the same length and share identical nodes. Here is a small code snippet. You may even want to convert this into a jquery plugin for your own uses.

jQuery(function($) {
// Two separate jQuery references
var divs = $("div");
var divs2 = $("div");


// They are equal
if (divs.length == divs2.length && divs.length == divs.filter(divs2).length) {


// They are not
} else {}
});

I stumbled on these answers and wondered which one was better. It all depends on your needs but the easiest to type, read and execute is the best of course. Here's the perf testcase I made to make a decision.

http://jsperf.com/jquery-objects-comparison