如何检查 2 个 jQuery 选择器是否指向相同的元素?
如果我尝试这样的事情:
$(".foo") === $(".foo") // = false
...我会犯错。如果我尝试这个查询,
$(".foo").get(0) === $(".foo").get(0) // = true
...我就明白了。
那是因为:
{a:myObject} !== {a:myObject};
[myObject] !== [myObject];
myObject === myObject;
我想知道是否有任何简洁的方法来测试这种相等性,最好内置于 jQuery 中。我编写的第二种方法只有在最多有一个元素与 .foo
匹配的情况下才能正确工作。该解决方案应该适用于任何数量的元素。
显然我不想只检查 ".foo" === ".foo"
因为我使用的实际选择更复杂。我只是在这个例子中简化了它们。 (例如,我可能想检查 $(this)
是否选择与 $(".foo")
相同的内容。)
If I try something such as this:
$(".foo") === $(".foo") // = false
... I get false. If I instead try this query,
$(".foo").get(0) === $(".foo").get(0) // = true
... I get true.
That's because:
{a:myObject} !== {a:myObject};
[myObject] !== [myObject];
myObject === myObject;
I'm wondering if there is any succinct way to test for this equality, preferably built into jQuery. The 2nd method I wrote only works correctly if there is at most one element which matches .foo
. The solution should work for any amount of elements.
Obviously I don't want to just check ".foo" === ".foo"
since the actual selections I'm using are more complicated. I just simplified them for this example. (E.g. I may want to check that $(this)
is selecting the same thing as $(".foo")
.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为您正在寻找
$().is
。 此处的文档。编辑:@lolwut为此答案提供了jsfiddle。阅读评论后,我更新了它并确定这个答案对于OP的情况并不可靠。
I think you are looking for
$().is
. Docs here.Edit: @lolwut provided a jsfiddle for this answer. After reading the comments, I updated it and determined that this answer isn't reliable for the OP's case.
核心库中没有任何内容可以检查 jQuery 对象的序列相等性,但是以下应该可以解决问题:
可以像这样使用:
为了完整性,可以像这样编写内容相等方法:
可以像这样使用:
There is nothing in the core library to check sequence equality of jQuery objects, however the following should do the trick:
Which would be useable like so:
For completeness, a contents equal method could be written like so:
Which would be useable like so:
如果您想检查两个集合是否包含完全相同相同的元素(可能顺序不同),则将
Array#every
与$.fn.index 结合使用
可以完成这项工作:If you want to check whether both sets contain exactly the same elements (possibly in a different order), then
Array#every
in combination with$.fn.index
could do the job:作为 pimvdb 答案的替代方案(这非常好,我只是为了完整性而提供此答案),您可以利用 add() 不会添加 jQuery 对象中已经存在的元素。因此,你可以写:
As an alternative to pimvdb's answer (which is very nice, I'm only providing this for completeness), you can leverage the fact that add() will not add elements that are already present in the jQuery object. Therefore, you can write:
好的,仅使用 jquery 内置函数,这似乎是正确的
if ($(oneSelector).is($(anotherSelector)))... 它们相等Ok, using only jquery builtins, this seems to be the right one
if ($(oneSelector).is($(anotherSelector)))... they are equal