2011-12-15 89 views
0

我想知道如何从另一个对象文本中的对象调用方法。这是我的代码。我正在构建一个jQuery UI滑块。我想打电话给动画中的animatebox功能物件常在我的铬控制台中的错误是:如何在两个JavaScript对象文字之间进行通信?

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?

+0

我没有得到那个错误,我无法想象为什么你会这样。代码看起来很好(假设“滑块”是一些插件;也许我猜jQuery UI)。 – Pointy 2011-12-15 14:29:28

+0

我不确定在sliderOpts中的change方法中对animateBox的调用。我看不到$ box.animations.animateBox是如何分配的 – tinyd 2011-12-15 14:33:51

+0

@Pointy是的。代码看起来是否适合你?是否有可能从这样的另一个对象内的一个对象调用一个函数?我不需要初始化什么吗? – 2011-12-15 14:34:04

回答

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


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

$box.animations - 是不确定的 - 它是如此

与包裹着一个jQuery对象ID =“消息”的元素,不具有动画属性

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

animations.animateBox(); 

,而不是$box.animations.animateBox()

0

你可以提供animateBox函数作为回调v ia选项。像这样:

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

然后在您的插件中设置滑块的animateBox值。如果使用标准的插件约定调用动画看起来在变化盒,如:

this.animateBox(); 
1

jQuery对象$框中有没有.animations财产。您已将动画定义为全局(窗口级别)变量。

由于您不会从animateBox函数返回任何内容,因此链接也不起作用。我想你想改变该函数返回$('#message')。一旦你的,而不是

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

尝试

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

你应该只能够调用animations.animateBox()。你还没有设置它作为jQuery方法,所以$box.animations可能是抛出错误。

相关问题