如何在 JavaScript 中使用 # 符号比较对象

How do i compare objects using # sign in javascript

本文关键字:符号 比较 对象 JavaScript      更新时间:2023-09-26

我正在使用一个函数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 子句不起作用!如何比较 2 个对象或其类型?

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

在jquery我们有.is方法,我认为它会帮助你

尝试以下方法:

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");
    }

jQuery对象本身始终是单独的对象,因此您有 查看每个jQuery中实际DOM数组的内容 对象。

参考: https://stackoverflow.com/a/7475132/1029506

你真的需要比较元素吗?你能比较一下选择器吗?

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");
    }
}