我如何使用 # sign in javascript 比较对象

How do i compare objects using # sign in javascript

我正在使用函数 hitTest(a,b);我给它 2 个对象。这些对象对应于我网页上具有 ID 的一些 div 个元素。

调用函数的地方:

if (hitTest($('#drawer'),$('#hit'+i)))

 {
  //do something...

}

这是函数本身

function hitTest(a, b) {
    if( $(b) == $('#hit5')   ){
        console.log("hit 5");
    }
    else if( $(b) == $('#hit4')   ){
        console.log("hit 4");
    }

    else if( $(b) == $('#hit6')   ){
        console.log("hit 6");
    }

问题是 if 子句的 none 有效!如何比较 2 个对象或它们的类型?

尝试以下方法:

function hitTest(a, b) {
    if( $(b)[0] === $('#hit5')[0]   ){
        console.log("hit 5");
    }
    else if( $(b)[0] === $('#hit4')[0]   ){
        console.log("hit 4");
    }

    else if( $(b)[0] === $('#hit6')[0]   ){
        console.log("hit 6");
    }

The jQuery objects themselves are always separate objects so you have to look at the contents of the actual DOM array inside each jQuery object.

参考:

if( $(b).is($('#hit5'))   ){
        console.log("hit 5");
    }
 

在 jquery 中我们有 .is 方法,我认为它会对您有所帮助

你真的需要比较元素吗?您可以只比较选择器吗?

if (hitTest('#drawer', '#hit'+i))

 {
  //do something...

}



function hitTest(a, b) {
    if( b === '#hit5') {
        console.log("hit 5");
    }
    else if( b === '#hit4') {
        console.log("hit 4");
    }
    else if( b === '#hit6') {
        console.log("hit 6");
    }
}