javascript 调用函数时如何设置jQuery this?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3945281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:47:35  来源:igfitidea点击:

How to set jQuery this when calling a function?

javascriptjquery

提问by slolife

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

使用 jQuery,我设置了一个链接标签的点击处理程序,如下所示:

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

handleClick does something like this:

handleClick 做这样的事情:

function handleClick() {
    var $this = $(this);
    ...
}

Now I have a need to directly call handleClick() outside of #lnk being clicked. Is there a way for me to set thiswhen calling handleClick?

现在我需要在点击 #lnk 之外直接调用 handleClick() 。有没有办法this在调用 handleClick 时进行设置?

回答by Felix Kling

You can use apply()or call():

您可以使用apply()call()

handleClick.call(theElementThatShouldBeThis);

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

但当然theElementThatShouldBeThis必须是 DOM 元素或被接受为jQuery().

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

如果你访问event里面的元素,它会变得更加棘手handleClick。但我会假设你没有;)

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

您还可以始终在#lnk通过调用$('#lnk').click()(模拟单击)的上下文中执行事件处理程序。

回答by Karim

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

我认为您正在寻找“致电”或“申请”:

Call

称呼

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

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

Apply

申请

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

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

From MDC

来自 MDC

var result = fun.apply(thisArg, [argsArray]);

or

var result = fun.call(thisArg[, arg1[, arg2[, ...]]]); 

回答by Roy Tinker

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

使用 Function.apply 并传入查询返回的 DOM 元素。

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

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

或者更好的是,让 jQuery 模拟对元素的点击(假设您已经附加了点击事件处理程序)。

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