确保两个项目在 JS / jQuery 中是同级的

发布于 2025-01-07 12:04:39 字数 358 浏览 2 评论 0原文

给定以下 HTML 结构:

<div class="wrap">
    <div id="a"></div>
    <div id="b"></div>
</div>

以下是错误的:

($('#a').parent() == $('#b').parent()); //=> false

即使:

$('#a').parent().children('#b').length; //=> 1

谁能解释为什么?谢谢!

Given the following HTML structure:

<div class="wrap">
    <div id="a"></div>
    <div id="b"></div>
</div>

the following is false:

($('#a').parent() == $('#b').parent()); //=> false

even though:

$('#a').parent().children('#b').length; //=> 1

Could anyone explain why? Thanks!

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

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

发布评论

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

评论(2

如日中天 2025-01-14 12:04:40

由于 $('#a) == $('#a')false 的原因相同,

每次 jQuery 构建一组元素时,它都会返回一个 < em>new 对象(即使 jQuery 对象包装了与另一个对象相同的元素)。在 JavaScript 中,只有一个对象与另一个对象相等的情况是它们是完全相同的对象;

var a = {
    foo: 1
};
var b = {
    foo: 1
};

(a == b) // false;

要解决此问题,您可以直接比较 DOM 对象(通过使用 .get(i) 或使用 jQuery 对象,例如数组 ([i])),或者使用 is() 方法;

if ($('.foo').get(i) == $('.bar').get(i));
if ($('.foo')[0] == $('.bar')[0]);
if ($('.foo').is($('.bar')); // or even...
if ($('.foo').is('.bar')); 

Because of the same reason that $('#a) == $('#a') is false

Each time jQuery builts a set of elements, it returns a new object (even if the jQuery object wraps the same elements as another). In JavaScript, the only time an object is equal to another, is if it's exactly the same object;

var a = {
    foo: 1
};
var b = {
    foo: 1
};

(a == b) // false;

To fix this, you can either compare the DOM objects directly (either by using .get(i) or using the jQuery object like an array ([i])), or you get use the is() method;

if ($('.foo').get(i) == $('.bar').get(i));
if ($('.foo')[0] == $('.bar')[0]);
if ($('.foo').is($('.bar')); // or even...
if ($('.foo').is('.bar')); 
与之呼应 2025-01-14 12:04:39

我并不是 100% 确切地知道它不起作用的原因,但我相信这是因为元素被包装在 jQuery 对象中,每个元素本质上是不同的。

作为解决方法,您可以比较本机 DOM 对象,如下所示:

($('#a').parent()[0] == $('#b').parent()[0]); // true

示例 fiddle

I'm not 100% on exactly why it doesn't work, but I believe it is because the elements are wrapped in jQuery objects which are inherently different per element.

As a workaround, you can compare the native DOM object, like this:

($('#a').parent()[0] == $('#b').parent()[0]); // true

Example fiddle

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