Match event.target with existing jQuery object

前端 未结 4 2037
走了就别回头了
走了就别回头了 2020-12-31 14:38

How can I do that?

event.target returns a HTML object,

and my element is a jQuery object.

Is there a better way to find out if event.tar

相关标签:
4条回答
  • 2020-12-31 14:41

    You can get the actual DOM element from the jQuery using .get(0) or simply the_element[0]. It would probably be better to check with jQuery, though.

    if (the_element.is(event.target))
    {
        ...
    }
    

    Using your example:

    $(document).click(function(event){
      if (the_element.is(event.target)) {
          return false;
      }
      if(($(event.target).parents().index(box) == -1) 
        && box.is(':visible')){
          close(); 
      }
    
    });
    
    0 讨论(0)
  • 2020-12-31 14:49

    Try -

    if(event.target === the_element[0])
    

    the_element[0] should unwrap your jQuery object and return a 'normal' DOM object, you can then compare it against the DOM object returned by event.target.

    0 讨论(0)
  • 2020-12-31 14:59

    Maybe I'm wrong, but it looks like nobody understood the question?... I also want to know how to GET JQUERY OBJECT on which I used listener function from the EVENT.TARGET, but not a DOM node for a jquery object!!)) So... I found not a very handy, but working solution:

    var elem = $('<input type="text" class="input" />');
    elem.focus( $.proxy( function( e )
    {
        this.onInpFocus( e, elem );
    }, this ) );
    

    And modified the listener's callback method to receive 2 arguments:

    onInpFocus : function( e, inp )
    

    Instead of using simple way like:

    elem.focus( $.proxy( this.onInpFocus, this ) );
    
    0 讨论(0)
  • 2020-12-31 15:05

    Actually, I found another way, much more handy one :) Just need to use the data argument:

    Data to be passed to the handler in event.data when an event is triggered.

    Now my code looks like this:

    var inp = $('<input type="text" />');
    inp.focus( { j : inp } , $.proxy( this.onInpFocus, this ) );
    
    //and the handler method
    onInpFocus : function( e )
    {
    var inp = e.data.j;
    ...
    }
    
    0 讨论(0)
提交回复
热议问题