使用JS / JQ类构造函数无法播放HTML音频元素

时间:2018-12-10 19:50:57

标签: jquery html5 html5-audio

我有以下HTML

<div data-song="song1" class="songs">
    <audio id="song1">
        <source src="audio/song1.mp3" type="audio/mpeg">
        Your browser does not support the audio element
    </audio>
</div>

<div data-song="song2" class="songs">
    <audio id="song2">
        <source src="audio/song2.mp3">
        Your browser does not support the audio element
    </audio>
</div>  

和以下Javascript / jQuery:

var songs={};
$(".songs").each(function(){
    let id=$(this).attr("data-song");
    let song=$("#" + id);
    songs[id]=new Music(song);
    songs[id].play();
})

function Music(song) {
    this.song=song;
    this.play=function(){song.play();};
}

当我尝试播放它们时,就像在$(elem)末尾一样,出现错误消息:

  

未捕获的TypeError:song.play不是函数      在Music.play(main.js:37)      在:1:15

我要去哪里错了?这看起来很简单。

1 个答案:

答案 0 :(得分:0)

我会尝试两种可能的解决方案之一:

解决方案1 ​​

var songs={};

$(".songs").each(function(){
    let id = $(this).attr("data-song");
    let song = $("#" + id)[0];
    songs[id] = new Music(song);
    songs[id].play();
});

function Music(song) {
    this.song=song;
    this.play=function(){song.play();};
}

解决方案2

var songs={};

$(".songs").each(function(){
    let id = $(this).attr("data-song");
    let song = $("#" + id);
    songs[id] = new Music(song);
    songs[id].play();
});

function isjQuery(obj) {
    return (obj && (obj instanceof jQuery || obj.constructor.prototype.jquery));
}

function Music(song) {
    this.song = isjQuery(song) ? song[0] : song;
    this.play = function(){song.play();};
}

第二个更强大。这样,您可以将Music与HTML元素或jQuery对象一起使用。

希望有帮助。