你会如何比较 jQuery 对象?

发布于 2024-08-25 17:05:47 字数 180 浏览 1 评论 0原文

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

这就是我所拥有的:

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

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

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.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

橙味迷妹 2024-09-01 17:05:47

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

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

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

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])
你如我软肋 2024-09-01 17:05:47

为什么不:

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

Why not:

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

?

我也只是我 2024-09-01 17:05:47

不需要循环,不需要测试单个第一个节点。除了确保它们具有相同的长度并共享相同的节点之外,几乎不需要任何其他操作。这是一个小代码片段。您甚至可能想将其转换为 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 {}
});

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 {}
});
往事风中埋 2024-09-01 17:05:47

我偶然发现了这些答案,想知道哪个更好。这完全取决于您的需求,但最容易输入、阅读和执行的当然是最好的。这是我为了做出决定而制作的性能测试用例。

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文