我想使用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>
元素?
答案 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()
答案 1 :(得分:0)
我使用以下方法:
var self = this;
example.find("li").each(function() {
var $li = $(this); // this is the <li>
self.someMethod(); // self is the context
});