如何在调用函数时设置jQuery? [英] How to set jQuery this when calling a function?

查看:55
本文介绍了如何在调用函数时设置jQuery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

handleClick做这样的事情:

handleClick does something like this:

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

现在我需要直接调用handleClick点击#lnk之外的()。有没有办法让我在调用handleClick时设置这个

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

推荐答案

您可以使用 apply() call()

You can use apply() or call():

handleClick.call(theElementThatShouldBeThis);

但当然 theElementThatShouldBeThis 必须是DOM jQuery()接受输入的元素或其他内容。

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

如果您正在访问它会变得更加棘手 handleClick 中的事件元素。但我只是假设你没有;)

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

你也可以在 #lnk 通过调用 $('#lnk')。click()(模拟点击)。

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

这篇关于如何在调用函数时设置jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆