链接到小提琴:http://jsfiddle.net/TungstenNo74/nCCMP/2/
可能是一个菜鸟问题,但我一直在寻找一段时间而且无法弄明白。
我正在尝试显示任意数量分数的条形图。我以为我会为每个分数初始化一个'bar'对象,然后为它构建一个条。
我无法弄清楚如何为每个单独的栏设置动画而不是整个.class(现在设置为'。test')
function bar(score, index,selector) {
this.score = score;
this.barHeight = score * 6;
}
bar.prototype.makeBar = function () {
$('#plot').append('<div class=test></div>');
};
bar.prototype.growBar = function () {
//$('.test').animate({ //This works, but it animates all of my bars...
$(this).animate({ //Why doesn't 'this' work?
'height': this.barHeight
}, 'slow', function () {});
};
var test = new bar(24, 0,'plot'); //Isn't this what 'this' refers to?
test.makeBar();
test.growBar();
答案 0 :(得分:3)
在您的完整小提示示例中,您可以看到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();
你可以这样做:
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});