因为在您的完整小提琴示例中,您可以看到这this
不是 jQuery 可以动画的实际 DOM 元素。
var plotHeight = $('#plot').css('height');
function bar(score, index) {
this.score = score;
this.index = index;
this.barHeight = score * 6;
}
bar.prototype.makeBar = function () {
$('#plot').append('<div class=test></div>');
};
bar.prototype.growBar = function () {
//$('.test').animate({
$(this).animate({ //Why doesn't 'this' work?
'height': this.barHeight
}, 'slow', function () {});
};
var test = new bar(24, 0); //score gives height, index does nothing... yet
test.makeBar();
test.growBar();
var test2 = new bar(15, 2); // This is just an object of type bar and does not hold a jQuery element to be animated.
test2.makeBar();
test2.growBar();
你可以这样做:
http://jsfiddle.net/nCCMP/3/
var plotHeight = $('#plot').css('height');
function bar(score, index,selector) {
this.score = score;
this.index = index;
this.barHeight = score * 6;
this.container = $(selector); // here is the DOM element
}
bar.prototype.makeBar = function () {
$('#plot').append('<div class=test></div>');
};
bar.prototype.growBar = function () {
//$('.test').animate({
$(this.container).animate({ //Now it will animate the element.
'height': this.barHeight
}, 'slow', function () {});
};
var test = new bar(24, 0,'#plot');
test.makeBar();
test.growBar();
var test2 = new bar(15, 2,'#plot');
test2.makeBar();
test2.growBar();
编辑:
I would try to write a jQuery plugin for that, it would probably start something like that:
(function ($) {
$.fn.scoreBar = function (options) {
var defaultVal = {
score,: 0,
index: '0'
};
var obj = $.extend(defaultVal, options);
return this.each(function () {
var selObject = $(this);
selObject.animate({ 'height': this.barHeight }, 'slow', function () {});
});
}
})(jQuery);
然后你这样称呼它:
$('#ScoreBarContainer').scoreBar({score=24,index=0});