如何检查两个变量是否引用同一个DOM对象

How to check if two variables refer to the same DOM object?

本文关键字:引用 是否 DOM 对象 变量 同一个 何检查 检查 两个      更新时间:2023-09-26

查看代码

var a = $('#element');
var b = $('#element');
a == b //false

如何检查ab是否引用了相同的dom元素?

问候!

使用此比较:

a[0] === b[0]

因为jQuery对象是DOM元素的某种包装器,实现了对它们的类似数组的访问。

尝试此比较

a[0] === b[0]

   'foo' === 'foo' // true as both operands are Type String (i.e. string primitives)
    var a = new String('foo');
    var b = new String('foo');
    a == b // false as a and b are Type Object and reference different objects
    a === b // false as a and b are Type Object and reference different objects
    a == 'foo' // true as a and 'foo' are of different type and, the Object (a) is converted to String 'foo' before comparison

检查Javascript比较运算符

你可以做:

if(a.is(b)){
   // do something
}

.is()方法将检查b是否为