jQuery 对象相等 [英] jQuery object equality

查看:28
本文介绍了jQuery 对象相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确定两个 jQuery 对象是否相等?我希望能够搜索特定 jQuery 对象的数组.

How do I determine if two jQuery objects are equal? I would like to be able to search an array for a particular jQuery object.

$.inArray(jqobj, my_array);//-1    
alert($("#deviceTypeRoot") == $("#deviceTypeRoot"));//False
alert($("#deviceTypeRoot") === $("#deviceTypeRoot"));//False

推荐答案

从 jQuery 1.6 开始,您可以使用 .is.以下是一年多前的回答...

Since jQuery 1.6, you can use .is. Below is the answer from over a year ago...

var a = $('#foo');
var b = a;


if (a.is(b)) {
    // the same object!
}

<小时>

如果你想看看两个变量是否实际上是同一个对象,例如:


If you want to see if two variables are actually the same object, eg:

var a = $('#foo');
var b = a;

...然后您可以检查他们的唯一 ID.每次创建一个新的 jQuery 对象时,它都会获得一个 id.

...then you can check their unique IDs. Every time you create a new jQuery object it gets an id.

if ($.data(a) == $.data(b)) {
    // the same object!
}

尽管使用简单的 a === b 也可以实现相同的效果,但以上内容至少可以向下一个开发人员展示您正在测试的内容.

Though, the same could be achieved with a simple a === b, the above might at least show the next developer exactly what you're testing for.

无论如何,这可能不是您想要的.如果你想检查两个不同的 jQuery 对象是否包含相同的元素集,你可以使用这个:

In any case, that's probably not what you're after. If you wanted to check if two different jQuery objects contain the same set of elements, the you could use this:

$.fn.equals = function(compareTo) {
  if (!compareTo || this.length != compareTo.length) {
    return false;
  }
  for (var i = 0; i < this.length; ++i) {
    if (this[i] !== compareTo[i]) {
      return false;
    }
  }
  return true;
};

来源

var a = $('p');
var b = $('p');
if (a.equals(b)) {
    // same set
}

这篇关于jQuery 对象相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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