Javascript 如何比较两个 jQuery 对象的身份?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6985932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:08:33  来源:igfitidea点击:

How do I compare two jQuery objects for identity?

javascriptjquery

提问by RonLugge

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).

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

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.

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

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

回答by qwertymk

You can also do:

你也可以这样做:

 if(val.is(this))

回答by nickf

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

使用该$()函数将始终创建一个新对象,因此无论如何,您的相等性检查总是会失败。

For example:

例如:

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

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

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

相反,您可以尝试只存储实际的 DOM 元素,因为它们只是在 jQuery 对象内部引用

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

回答by ShankarSangoli

Try this:

尝试这个:

function openBox(index)
{
val=$('#box'+index);
$('.profilePageContentBox').each(function(){
    if($(this).is(":visible"))
    {
        if(!$(this).is("#box"+index))
            $(this).slideToggle(200);
    }
});
val.slideToggle(200);
}