如何代理匿名函数,以便“this”关键字都可用?

时间:2014-09-06 11:06:16

标签: jquery

我想使用jQuery.proxy方法为匿名函数提供上下文。同时我希望代理原始函数的上下文可用。

考虑这个例子:

example.find("li").each($.proxy(function(i) {
    var context = this; // Great! This gives me the context of the function call as expected.
    var $li = '???'; // How can I access the jQuery element of the <li>? $(this) obviously won't do.
}, this));

我如何在这里访问迭代的<li>元素?

2 个答案:

答案 0 :(得分:3)

将第二个参数用于.each回调

example.find("li").each($.proxy(function(i, el) {
    var context = this; // Great! This gives me the context of the function call as expected.
    var $li = $(el);
}, this));

.each()

documentation

答案 1 :(得分:0)

我使用以下方法:

var self = this;
example.find("li").each(function() {
    var $li = $(this); // this is the <li>
    self.someMethod(); // self is the context
});