附加元素的getelementbyid

时间:2014-10-20 08:27:42

标签: javascript audio element

var track_url = data.result;

SC.get('/resolve', {
    url: track_url
}, function(track) {
    console.log(track.id);
    $('#player').append('<iframe id="soundcloud_widget"  src="http://w.soundcloud.com/player/?url=https://api.soundcloud.com/tracks/' + track.id + '&show_artwork=true&liking=true&sharing=true&auto_play=true"  width="1280"  height="720"   frameborder="no"></iframe>');
    var q = $('#player').get(0);
    console.log(q);
    var widget = SC.Widget(document.getElementById('soundcloud_widget'));
    widget.bind(SC.Widget.Events.READY, function() {
        console.log("test1");
    });
    widget.bind(SC.Widget.Events.FINISH, function() {
        console.log("test2");
    });
});

我正在使用此代码在我的页面上动态嵌入soundcloud播放器。每次请求新歌时,它都会删除之前播放的div元素并将其重新出现在HTML中,以便您可以播放新歌。我有这个为youtube API工作,但无法让它为soundcloud工作。事件不会发生。我在这一行收到错误:

var widget = SC.Widget(document.getElementById('soundcloud_widget'));

错误是:

Uncaught TypeError: undefined is not a function ?n=2071:211(anonymous function) ?n=2071:211(anonymous function) sdk.js:1request.onreadystatechange sdk.js:1

现在我相信这个错误正在发生,因为当我追加新的iframe时,DOM数据没有被更新,因此'gecln_by于'getelementbyid'找不到'soundcloud_widget'元素。不幸的是,这是我自己可以得到的。

1 个答案:

答案 0 :(得分:0)

 var track_url = data.result;

SC.get('/resolve', {
    url: track_url
}, function(track) {
    console.log(track.id);
    $('#player').append('<iframe id="soundcloud_widget"  src="http://w.soundcloud.com/player/?url=https://api.soundcloud.com/tracks/' + track.id + '&show_artwork=true&liking=true&sharing=true&auto_play=true"  width="1280"  height="720"   frameborder="no"></iframe>');
    var q = $('#player').get(0);
    console.log(q);

    var element = $('#soundcloud_widget');
    var widget = SC.Widget(element);
    widget.bind(SC.Widget.Events.READY, function() {
        console.log("test1");
    });
    widget.bind(SC.Widget.Events.FINISH, function() {
        console.log("test2");
    });
});

尝试吐出元素的获取

  

var element = $('#soundcloud_widget');

使用元素

var widget = SC.Widget(element);

这应该会更好地给你错误。