javascript - 使用 $.proxy javascript 调用函数

标签 javascript jquery html proxy

我想使用 $.proxy 在点击事件上加载函数。 如果我使用下面的单击事件加载该函数,那么一切正常。

点击事件正在运行

$('element').click($.proxy(this.doProcess, this));

点击事件不起作用

$('element').click(function(){
    // Perform other things
    $.proxy(this.doProcess, this);  
});

正如您所看到的,我想在加载函数之前对单击事件执行其他操作。您能帮我弄清楚为什么如果我使用“.click(function()...”而不是简单地使用“.click()..”则无法加载

最佳答案

因为在第一个片段中,单击函数调用返回的函数。在第二个代码片段中,您将当前的 this 值绑定(bind)到该函数,但不调用返回的函数。您可以使用调用运算符 (()) 来调用该函数:

$.proxy(this.doProcess, this)();  

请注意,匿名函数(即当前事件处理程序)上下文中的 this 并不引用外部上下文的 this 关键字的值,您可以可以缓存值:

var that = this;
$('element').click(function() {
    // Perform other things
    $.proxy(that.doProcess, this)(/* arguments go here */);  
//           |               |
//           |               ----- refers to the clicked element
//           ----- reference of the outer context's `this` value
});

关于javascript - 使用 $.proxy javascript 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26940796/

相关文章:

javascript - Highcharts 单个水平堆叠条形图,始终显示数据名称(标签)和百分比,鼠标悬停时显示数据编号和系列名称

jquery - 弹出新对话框而不重定向到另一个页面,如 IMDb 登录

html - 使用htaccess将所有请求重定向到主页(隐藏URL中的index.html)

javascript - 欧芹错误消息类覆盖

javascript - 缩放旋转的矩形并找到新的控制点和中心

jquery - 如何点击 iframe 将其删除?

html - CSS "hover"显示奇怪的字符

javascript - 倒退消失后如何让时钟出现在屏幕上

javascript - wp_enqueue_script - 渲染页面源代码中的文件路径丢失 "/"

javascript - 向附加元素添加删除按钮