0

链接到小提琴:http: //jsfiddle.net/TungstenNo74/nCCMP/2/

可能是一个菜鸟问题,但我一直在寻找一段时间,只是无法弄清楚。

我正在尝试为任意数量的分数显示条形图。我在想我会为每个分数初始化一个“条形”对象,然后为它构建一个条形。

我不知道如何为每个单独的栏而不是整个 .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();
4

1 回答 1

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();

你可以这样做:

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});
于 2013-04-17T10:34:09.557 回答