2011-12-15 157 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可能是拋出錯誤。

相關問題