为什么$(" body")== $(" body")返回false? [英] Why does $("body") == $("body") return false?

查看:157
本文介绍了为什么$(" body")== $(" body")返回false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么标题中的等式是假的?如何检查两个jQuery选择器是否指向同一个DOM对象?

How come the equation in the title is false? How do check if two jQuery selectors point to the same DOM object?

推荐答案

您正在比较两个 distinct jQuery对象,因为你调用 $()两次(对于等式的每一边一次),并且正如MooGoo所解释的那样 jQuery每次调用它时都会创建新的包装器对象。这就是比较最终返回false的原因。

You are comparing two distinct jQuery objects because you call $() twice (once for each side of the equation), and as MooGoo explains jQuery creates new wrapper objects for each time you call it. That's why the comparison ends up returning false.

您可以使用 get() 或数组解除引用,然后比较这些元素。以下两者都返回true,因为两个相同的选择器匹配相同的 body DOM元素:

You can extract a DOM object from each jQuery object by either using get() or array dereferencing, then compare these elements. The following both return true because both identical selectors match the same body DOM element:

$('body').get(0) == $('body').get(0)
$('body')[0] == $('body')[0]

如果要针对jQuery选择器进行测试,请使用 是() 。请注意,除非您的选择器相同,否则您使用的选择器可能不一定匹配相同的DOM元素(使用上面的选项仍然更好)。这也返回true:

If you want to test against a jQuery selector, use is(). Note that, unless your selectors are identical, the selectors you use may not necessarily match the same DOM elements (it's still better to use the above). This also returns true:

$('body').is('body')

这篇关于为什么$(" body")== $(" body")返回false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆