如何在两个javascript对象文字之间进行通信?

问题描述 投票:0回答:5

我想知道如何从另一个对象文字中的对象调用方法。 这是我的代码。 我正在构建一个jQuery UI滑块。 我正在尝试在animations对象文字中调用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的方法?

javascript jquery-ui-slider
5个回答
2
投票

$box.animations未定义-确实如此

带有jQuery对象的id =“ message”元素没有动画属性

您可以通过简单地致电来解决

animations.animateBox();

而不是$box.animations.animateBox()


1
投票

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

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

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

尝试

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

1
投票

您应该只能够调用animations.animateBox() 。 您尚未将其设置为jQuery方法,因此$box.animations很可能$box.animations错误。


1
投票
var animations = {
    animateBox: function (obj) {
        obj.slideDown(500);
    }
};


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

0
投票

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

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

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

this.animateBox();
© www.soinside.com 2019 - 2024. All rights reserved.