你会如何比较 jQuery 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2436966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:30:54  来源:igfitidea点击:

How would you compare jQuery objects?

jquerycompare

提问by Kyle Hotchkiss

So I'm trying to figure out how to compare two jQuery objects, to see if the parent element is the body of a page.

所以我想弄清楚如何比较两个 jQuery 对象,看看父元素是否是页面的主体。

here's what I have:

这是我所拥有的:

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

I know this is wrong, but if anybody understands what I'm getting at, could they point me towards the correct way of doing this?

我知道这是错误的,但如果有人理解我的意思,他们能指出我这样做的正确方法吗?

回答by CMS

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

您需要比较原始 DOM 元素,例如:

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

or

或者

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

回答by cletus

Why not:

为什么不:

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

?

?

回答by tbranyen

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 插件供您自己使用。

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 {}
});

回答by Salketer

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

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