繁体   English   中英

我如何使用#登录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子句都不起作用! 如何比较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");
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM