我想知道如何更改 jQuery 回调函数的上下文,以便 this
与父函数中的相同。
看下面的例子:
var context = this;
console.log(context);
element.animate(css, speed, type, function () {
var new_context = this;
console.log(new_context);
});
如何使 new_context
等于 context
?
我意识到我可以做到这一点:
var new_context = context;
但是有没有更好的方法来告诉函数使用不同的上下文?
最佳答案
您可以利用闭包:
var context = this;
console.log(context);
element.animate(css, speed, type, function () {
var new_context = context; // Closure
console.log(new_context);
});
您还可以这样做:
// First parameter of call/apply is context
element.animate.apply(this, [css, speed, type, function () {
var new_context = this;
console.log(new_context);
}]);
关于javascript - jQuery 更改回调上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14212414/