jQuery:在 $.proxy 内查找左侧偏移量
this.progress.click(function(e) { // works
var seek = (e.pageX - this.offsetLeft) / $(this).width();
self_ref[index].seek(seek * self_ref[index].source.duration);
});
this.progress.click($.proxy(function(e) { // doesn't work
var seek = (e.pageX - this.offsetLeft) / $(this).width();
this.seek(seek * this.source.duration);
}, this));
this.offsetLeft
在第一个示例中有效,但在第二个示例中无效。我需要 $.proxy
,所以我无法摆脱它。一旦上下文在函数内部发生更改,我就找不到让 this.offsetLeft
工作的方法。
PS:由于我正在开发扩展,我无法再继续使用 self_ref[index]
。
this.progress.click(function(e) { // works
var seek = (e.pageX - this.offsetLeft) / $(this).width();
self_ref[index].seek(seek * self_ref[index].source.duration);
});
this.progress.click($.proxy(function(e) { // doesn't work
var seek = (e.pageX - this.offsetLeft) / $(this).width();
this.seek(seek * this.source.duration);
}, this));
this.offsetLeft
works in the first example but not in the second. I need $.proxy
, so I can't get rid of it. I can't find a way to get this.offsetLeft
to work once the context has been changed inside it's function.
PS: I can no longer go back to using self_ref[index]
because of an extensions I'm working on.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要么像 Dennis 所说的那样在外部作用域中保留
this
的副本,要么使用e.currentTarget
来获取正在处理事件的 DOM 元素。在您的第一个示例中(非代理):
this == e.currentTarget
Either keep a copy of
this
in the outer scope like Dennis says, or usee.currentTarget
to get the DOM element that is handling the event.in your first example (non proxied):
this == e.currentTarget
第一个示例中的
this
指的是被单击的元素。在第二个中,您使用它来引用被单击的元素以及将函数代理到的对象。您可以在创建处理程序并创建闭包时通过重命名this
来修改原始的工作示例:this
in the first example refers to the element that was clicked. In the second, you are using it both to refer to the element that was clicked, as well as the object you are proxying the function to. You can modify the original, working example by renamingthis
when you create the handler and creating a closure:编辑:其他两个答案显然都比这个好得多。尊重:-)
,
this
是被单击的DOMElement:this.progress
在第一个工作示例中 第二个示例,当使用
$.proxy
时,this
引用周围上下文,而不是progress
元素。因此,在代理处理程序中,您应该使用:
而不是
this.offsetLeft
。Edit: both other answers are obviously far way better that this one. Respect :-)
In the first working example,
this
is the DOMElement that was clicked:this.progress
In the second example, when using
$.proxy
,this
refers to the surrounding context, not theprogress
element anymore.So within the proxified handler, you should be using:
instead of
this.offsetLeft
.