比较jQuery对象 [英] comparing jQuery objects

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

问题描述

我正在使用选择器来获取一组对象(0或更多):

I'm using a selector to get a group of objects (0 or more):

var $openMenus = $Triggers.filter(".trigger-hover");

然后我有一个事件附加到上面对象中可能存在或可能不存在的项目。在该事件中,我想将触发事件的项目与c

Then I have an event attached to an item that may or may not be in the object above. Within that event where I want to compare the item that triggers the event to c

$([selector])
    .focus(function(){
        var $thisMenu = $(this);
        $openMenus.each(function(){
            if ($(this) != $thisMenu ){ 
                [do something]
            }
        }) 
    })

这不起作用。虽然多个jQuery对象可能会引用相同的DOM对象,但它们实际上是单独的jQuery对象,并且永远不会比较真实。

This will not work. While multiple jQuery objects may REFER to the same DOM object, they are actually separate jQuery objects and there for will never compare true.

鉴于此,将会有什么方法处理这个(事情?如何有两个jQuery对象并比较它们以查看一个jQuery对象是否引用了与另一个相同的DOM元素?

Given that, what would be the way to handle this? How does one have two jQuery objects and compare them to see if one jQuery object refers to the same DOM element as another?

我可以给出我想要的每个项目选择一个ID,但我想知道是否有其他方法可以解决这个问题,而无需在HTML中添加更多内容。

I could give each item I'm trying to select an ID, but am wondering if there is another way to go about it without having to add more to the HTML.

推荐答案

我不知道为什么你不想要id值,但你总是可以创建一个小jQuery插件,如果它们缺少原始HTML中的值,则给元素提供唯一的id值。

I don't know why you wouldn't want "id" values, but you could always make a little jQuery plugin to give elements unique "id" values if they're missing values from the original HTML.

jQuery.fn.setId = (function setupSetId() {
  var counter = 0; // or maybe new Date().getTime()
  return function setId() {
    return this.each(function setIdInternal() {
      var $self = jQuery(this);
      if (!$self.attr('id')) $self.attr('id', '_' + counter++);
    });
  };
})();

然后你可以编写另一个实用程序来按元素id比较jQuery数组。

Then you can write another utility to compare jQuery arrays by element id.

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

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