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

时间:2014-04-29 16:59:29

标签: javascript dom

查看代码

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

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

问候!

3 个答案:

答案 0 :(得分:2)

通过这种比较:

a[0] === b[0]

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

答案 1 :(得分:2)

尝试这种比较

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 Comparison Operators

答案 2 :(得分:1)

你可以这样做:

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

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