如何比较两个jQuery对象的身份? [英] How do I compare two jQuery objects for identity?

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

问题描述

我正在尝试使用jQuery在网页上打开/关闭控件'框'。不幸的是,如果用户碰巧点击已经打开的盒子,关闭一个盒子只是为了重新打开它看起来不太好。 (盒子互相排斥)。

I'm trying to use jQuery to open / close control 'boxes' on a webpage. Unfortunately, it doesn't look very good to close a box just to re-open it if the user happens to click on the already opened box. (Boxes are mutually exclusive).

我使用的代码不起作用,我不知道为什么。我仍然得到一个盒子关闭只是为了重新打开,这不是所需的功能。我为调试目的创建了'val'变量;在调试器中,它显示'val'与$(this)具有完全相同的值,这应该阻止它在if语句中到达 .slideToggle()但是没有。

The code I'm using doesn't work, and I'm not sure why. I still get a box closing just to open up anew, which isn't the desired functionality. I created the 'val' variable for debugging purposes; in the debugger, it shows 'val' as having the exact same value as $(this), which should prevent it from getting to the .slideToggle() inside the if statement, but doesn't.

function openBox(index)
{
  val = $('#box' + index);
  $('.profilePageContentBox').each(function(){
      if($(this).css('display') != 'none')
      {
        if($(this) != val)
        {
          $(this).slideToggle(200);
        }
      }
    });
  val.slideToggle(200);
}


推荐答案

使用 $()函数将始终创建一个新对象,所以不管怎样,你的相等检查总会失败。

Using the $() function will always create a new object, so no matter what, your equality check there will always fail.

例如:

var div = document.getElementById('myDiv');

$(div) === $(div);   // false!

相反,你可以尝试只存储实际的DOM元素,因为那些只是引用到jQuery对象里面。

Instead, you could try just storing the actual DOM elements, since those are just referred to inside jQuery objects.

val = $('#box'+index).get(0);
...
if (this !== val) { }

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

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