0

我想知道如何从另一个对象文字中的对象调用方法。这是我的代码。我正在构建一个 jQuery UI 滑块。我正在尝试在动画对象文字中调用animatebox函数,而我的 chrome 控制台中的错误是:

Uncaught TypeError: Cannot call method 'animateBox' of undefined

我的代码如下所示:

var sliderOpts = {

    animate: true,
    range: "min",
    value: 50,
    min: 10,
    max: 100,
    step: 10,

    //this gets a live reading of the value and prints it on the page
    slide: function (event, ui) {
        $("#slider-result").html(ui.value + " GB");
    },

    //this updates the hidden form field so we can submit the data using a form
    change: function (event, ui) {
        $('#hidden').attr('value', ui.value);
        var val = ui.value,
            $box = $('#message');
        switch (true) {
        case (val > 50):
            $box.animations.animateBox().html('you have chosen xtremenet');
            break;
        case (val < 50):
            $box.fadeOut().fadeIn().html('you have chosen valuenet');
            break;
        default:
            $box.fadeOut().fadeIn().html('you have chosen powernet');
        }
    }
};

var animations = {
    animateBox: function () {
        $("#message").slideDown(500);
    }
};

$(".slider").bind("slidecreate", animations.animateBox).slider(sliderOpts);

那么如何调用这个名为 animateBox 的方法呢?

4

5 回答 5

2

$box.animations- 未定义 - 就是这样

id="message" 用 jQuery 对象包裹的元素,没有动画属性

在你的情况下,你可以通过简单地调用来修复它

animations.animateBox();

代替 $box.animations.animateBox()

于 2011-12-15T14:32:59.413 回答
1

jquery 对象 $box 没有 .animations 属性。您已将动画定义为全局(窗口级)变量。

链接也不起作用,因为您没有从 animateBox 函数返回任何内容。我猜您想更改该函数以返回 $('#message')。一旦你有了它,而不是

$box.animations.animateBox().html('you have chosen xtremenet');

尝试

animations.animateBox().html('you have chosen xtremenet');
于 2011-12-15T14:33:21.460 回答
1

你应该可以打电话animations.animateBox()。您尚未将其设置为 jQuery 方法,因此$box.animations很可能是引发错误的原因。

于 2011-12-15T14:34:15.210 回答
1
var animations = {
    animateBox: function (obj) {
        obj.slideDown(500);
    }
};


animations.animateBox($box.html('you have chosen xtremenet'))
于 2011-12-15T14:35:16.723 回答
0

您可以通过选项提供 animateBox 函数作为回调。像这样:

var sliderOpts = {
    animateBox: function() { // magic here },
    animate: true,
    range: "min",
    ...
};

然后在插件中设置滑块的 animateBox 值。如果您使用标准插件约定,则更改动画框的调用如下所示:

this.animateBox();
于 2011-12-15T14:33:16.203 回答