我正在尝试在我的应用程序中包装集中调用jQuery .animate
$('#' + this.elmItem).animate({"top": moveTo}, speed, function() {
var item = scope.getItemSizeDom();
scope.saveItemSize(item);
}); // This works
我试图用一个没有成功的方法包装,你能告诉我我在做错了一个如何修复它的例子吗?
this.itemAnimate = function(direction, moveTo, speed) {
$('#' + this.elmItem).animate({direction: moveTo}, speed, function() {
var item = scope.getItemSizeDom();
scope.saveItemSize(item);
});// This does not work
};
this.itemAnimate("top", moveTo, "fast");
答案 0 :(得分:2)
您可以将object作为参数传递给animate方法:
this.itemAnimate = function (direction, moveTo, speed) {
var param = {};
param[direction] = moveTo;
$('#' + this.elmItem).animate(param, speed, function () {
var item = scope.getItemSizeDom();
scope.saveItemSize(item);
}); // This does not work
};
答案 1 :(得分:1)
您需要创建一个基本的jQuery插件:
$.fn.itemAnimate = function(direction, moveTo, speed) {
var params = {};
params[direction] = moveTo;
$(this).animate(params, speed, function() {
//do something here
});
};
然后叫它:
$("whatever").itemAnimate("top", moveTo, "fast");
答案 2 :(得分:0)
该函数不知道this
是什么,因为它没有上下文。给它这样的上下文:
this.itemAnimate.apply(this, ["top", moveTo, "fast"]);
而不是
this.itemAnimate("top", moveTo, "fast");
但是如果你将this
别名到其他变量会更好,所以它不会在范围链中丢失。
var my_thing = this; // be descriptive about what it is exactly.
my_thing.itemAnimate.apply(my_thing, ["top", moveTo, "fast"]);