2014-02-16 27 views
0

我試圖寫一個腳本,一旦按下按鈕,它就會顯示SoundCloud中歌曲的持續時間。我也對這些API有點麻煩。我已閱讀並重讀關於某個「回調」的行傳遞了一個參數,但我仍然不明白。 「因此,每個getter方法都會接受一個回調函數作爲參數,當被調用時,它將被賦予getter方法的返回值。」SoundCloud Getters - getDuration

這裏是我在我的代碼。我知道它不漂亮,但我只是想讓這件事情起作用。

<!doctype html> 
    <html> 
    <head> 
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
     <script src="http://w.soundcloud.com/player/api.js"></script> 
     <script> 
     $(document).ready(function() { 
     var widget = SC.Widget(document.getElementById('playing')); 
     widget.bind(SC.Widget.Events.READY, function() { 
      console.log('Ready...'); 
     }); 

     $('button').click(function() { 
      widget.getDuration(function(sound)); 
     }); 
     }); 

     function sound(var time) { 
     document.write(time); 
     } 
     </script> 
    </head> 
    <body> 
       <iframe id="playing" 
       width="500" 
       height="400" scrolling="no" 
       frameborder="yes" 
       src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/66816173&amp;auto_play=false&amp;hide_related=false&amp;visual=true"> 
       </iframe> 
     <button>Play/Pause</button> 
    </body> 
    </html> 

回答

1

你的代碼中有兩個錯誤的函數定義。 在developer.mozilla.org上你可以找到一些很好的javascript文檔。 特別是,此頁面上,你可以學習如何正確地定義功能: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

返回代碼:

1)getDuration的SoundCloud函數接受回調。 function(sound)不是有效的函數定義。

2)函數定義不參數名

下面是兩個更正你的代碼之前需要var關鍵字。它可以像你所期望的那樣工作。

var widget = SC.Widget(document.getElementById('playing')); 
    widget.bind(SC.Widget.Events.READY, function() { 
     console.log('Ready...'); 
    }); 

    $('button').click(function() { 
     widget.getDuration(function(duration){ 
      alert(duration); 
     }); 
    }); 
}); 

,在這裏你可以看到工作小提琴:http://jsfiddle.net/Ldc2N/

一件事:我看到,在什麼應該是回調,你叫document.write

function sound(time) { document.write(time); } 

請考慮它只在文檔尚未準備好時將內容追加到文檔中。文檔準備就緒時調用int將完全覆蓋其內容。

+0

啊好吧。真棒!非常感謝! – user3316362

+0

不客氣。如果你發現答案有用,請考慮投票(這就是stackoverflow的工作方式;-))。謝謝。 –

+0

我會如何去做這個沒有按鈕?只要頁面加載彈出窗口顯示出來? – user3316362