jQuery对象相等 [英] jQuery object equality

查看:111
本文介绍了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开始,您可以使用 .以下是一年多以前的答案...

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天全站免登陆