比较jQuery对象

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

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

然后我有一个事件附加到上面的对象中可能或可能不在的项目。 在那个我希望将触发事件的项目与c进行比较的事件中

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

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

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

我可以给每个项目,我正在尝试选择一个ID,但我想知道是否有其他方法去做,而不必添加更多的HTML。

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

 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数组。

从bobince继续,而不是使用wrapper [0]使用正确的get(0)方法返回存储在jQuery对象中的第一个元素。

 var focused = null; $(':input').focus( function() { focused = $(this); compare($(this)); //Compare them...trivial but will return true despite being different jQuery objects. }).blur( function() { focused = null; }); function compare(element) { if (element.get(0) == focused.get(0)) { alert('The same'); } } 

您无法在jQuery包装器上进行比较,但您可以在底层DOM节点上进行比较。 失去几美元,你很好:

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

(或使用例如wrapper[0]从单项jQuery包装器获取DOM节点。)

(我使用===进行比较,因为它通常是最好的,但在这种情况下它也适用于== 。)

要比较DOM元素,您应该比较原始元素,它们可以作为数组中的第一个元素,例如:$(’。test’) [0]

所以在你的情况下,代码应如下所示:

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

jQuery对象无法直接比较,但这可以通过使用.add()或.not()操作轻松实现:

 var $thisMenu = $(this); $openMenus.each(function(){ if ($(this).add( $thisMenu ).length == 1 ){ [do something] } }) 

要么

 var $thisMenu = $(this); $openMenus.each(function(){ if ($(this).not( $thisMenu ).length == 0 ){ [do something] } }) 

您可以使用jQuery中的.siblings()函数解决此问题。 这样你可以避免比较对象。

 $(this).mouseenter( function(){ //use functions you want to replace "someFunctionHere" $(this).siblings().find('ul').someFunctionHere(); //do something else... } );