How to set jQuery this when calling a function?

前端 未结 3 1148
深忆病人
深忆病人 2021-01-04 11:27

Using jQuery, I set a link tag\'s click handler like this:

$(\'#lnk\').click(handleClick);

handleClick does something like this:

         


        
相关标签:
3条回答
  • 2021-01-04 12:15

    You can use apply() or call():

    handleClick.call(theElementThatShouldBeThis);
    

    But of course theElementThatShouldBeThis must be a DOM element or something that is accepted as input for jQuery().

    And it becomes more tricky if you are accessing the event element inside handleClick. But I will just assume you don't ;)

    You can also always execute the event handler in the context of #lnk by calling $('#lnk').click() (which simulates a click).

    0 讨论(0)
  • 2021-01-04 12:24

    I think you're looking for "call" or "apply":

    Call

    https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call

    Apply

    https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply

    From MDC

    var result = fun.apply(thisArg, [argsArray]);
    
    or
    
    var result = fun.call(thisArg[, arg1[, arg2[, ...]]]); 
    
    0 讨论(0)
  • 2021-01-04 12:28

    Use Function.apply and pass in the DOM element returned by the query.

    handleClick.apply($('#lnk')[0]);
    

    Or better yet, let jQuery simulate a click on the element (Assuming you've already attached the click event handler).

    $('#lnk').click();
    
    0 讨论(0)
提交回复
热议问题