确保两个项目在 JS / jQuery 中是同级的
给定以下 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于
$('#a) == $('#a')
为false
的原因相同,每次 jQuery 构建一组元素时,它都会返回一个 < em>new 对象(即使 jQuery 对象包装了与另一个对象相同的元素)。在 JavaScript 中,只有一个对象与另一个对象相等的情况是它们是完全相同的对象;
要解决此问题,您可以直接比较 DOM 对象(通过使用
.get(i)
或使用 jQuery 对象,例如数组 ([i]
)),或者使用is()
方法;Because of the same reason that
$('#a) == $('#a')
isfalse
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;
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 theis()
method;我并不是 100% 确切地知道它不起作用的原因,但我相信这是因为元素被包装在 jQuery 对象中,每个元素本质上是不同的。
作为解决方法,您可以比较本机 DOM 对象,如下所示:
示例 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:
Example fiddle