Javascript 如何比较jquery中的两个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2407825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:11:28  来源:igfitidea点击:

how to compare two elements in jquery

javascriptjquerydom

提问by zjm1126

var a=$('#start > div:last-child');
var b=$('#start > div.live')[0];
alert(a==b)
alert(a==$(b))

It's always false. How can you compare two elements in jQuery?

它总是假的。如何比较 jQuery 中的两个元素?

thanks

谢谢

回答by e-motiv

For the record, jQuery has an is()function for this:

作为记录,jQuery 有一个is()函数:

a.is(b)

Note that ais already a jQuery instance.

请注意,a它已经是一个 jQuery 实例。

回答by Darin Dimitrov

You could compare DOM elements. Remember that jQuery selectors return arrays which will never be equal in the sense of reference equality.

您可以比较 DOM 元素。请记住,jQuery 选择器返回的数组在引用相等的意义上永远不会相等。

Assuming:

假设:

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

this:

这个:

$('div.a')[0] == $('div#a')[0]

returns true.

返回真。

回答by Anurag

Every time you call the jQuery() function, a new object is created and returned. So even equality checks on the same selectors will fail.

每次调用 jQuery() 函数时,都会创建并返回一个新对象。因此,即使是对相同选择器的相等检查也会失败。

<div id="a">test</div>

$('#a') == $('#a') // false

The resulting jQuery object contains an array of matching elements, which are basically native DOM objects like HTMLDivElementthat always refer to the same object, so you should check those for equality using the array index as Darin suggested.

生成的 jQuery 对象包含一个匹配元素数组,这些元素基本上是本地 DOM 对象,就像HTMLDivElement总是引用同一个对象一样,因此您应该使用 Darin 建议的数组索引检查它们是否相等。

$('#a')[0] == $('#a')[0] // true

回答by Jondi

a.is(b)

and to check if they are not equal use

并检查它们是否不等价使用

!a.is(b)

as for

至于

$b = $('#a')
....
$('#a')[0] == $b[0] // not always true

maybe class added to the element or removed from it after the first assignment

可能在第一次赋值后将类添加到元素或从元素中删除

回答by gnarf

Random AirCoded example of testing "set equality" in jQuery:

在 jQuery 中测试“设置相等”的随机 AirCoded 示例:

$.fn.isEqual = function($otherSet) {
  if (this === $otherSet) return true;
  if (this.length != $otherSet.length) return false;
  var ret = true;
  this.each(function(idx) { 
    if (this !== $otherSet[idx]) {
       ret = false; return false;
    }
  });
  return ret;
};

var a=$('#start > div:last-child');
var b=$('#start > div.live')[0];

console.log($(b).isEqual(a));

回答by Frank Schwieterman

The collection results you get back from a jQuery collection do not support set-based comparison. You can use compare the individual members one by one though, there are no utilities for this that I know of in jQuery.

您从 jQuery 集合返回的集合结果不支持基于集合的比较。您可以使用一个一个的比较单个成员,但我知道在 jQuery 中没有用于此的实用程序。