Compare 'e.target' to a jQuery object

后端 未结 4 1414
情书的邮戳
情书的邮戳 2021-02-06 22:00

What I want to do:

( clickedObject === someDiv ) //returns true or false

What I tried

( $(e.target) === $(\'.selector\') ); //r         


        
4条回答
  •  情书的邮戳
    2021-02-06 22:42

    You're close. Use .is() instead:

    if($(e.target).is('.selector')) {
        // Your code
    }
    

    The trick here is that you wrap e.target in a jQuery object to allow it access to all the useful jQuery methods.

    If you're just seeing whether e.target has a certain class, try using .hasClass() in place of .is():

    if($(e.target).hasClass('selector')) {
        // Your code
    }
    

    Either method works, although .hasClass() is a little clearer as to what the code does, and is faster than using .is()

提交回复
热议问题