我正在编写一个脚本,一旦按下按钮,它就会显示来自SoundCloud的歌曲的持续时间。我在API方面也遇到了一些小麻烦。我已经阅读并重新阅读了关于某些“回调”传递一个参数的行,但我仍然不明白。正因为如此,每个getter方法都接受一个回调函数作为参数,当调用该参数时,将给出getter方法的返回值。
这是我的密码所在。我知道这不漂亮,但我只是想让这该死的东西发挥作用。
<!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&auto_play=false&hide_related=false&visual=true">
</iframe>
<button>Play / Pause</button>
</body>
</html>
发布于 2014-02-16 16:19:36
代码中有两个错误的函数定义。在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完全覆盖其内容。
https://stackoverflow.com/questions/21813762
复制相似问题