所以我有一个 div,单击它时会播放 mp3 声音。而不是玩一次。它继续一遍又一遍地播放。代码片段是:
$(".g-contain").click(function() {
audioElement.play();
});
这可能无关紧要,但我想我应该向您展示整体代码:
/* set no cache */
$.ajaxSetup({ cache: false });
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'https://www.dropbox.com/s/k8xaglyd48vbnq1/pacman_chomp.mp3?dl=1');
audioElement.addEventListener('ended', function() {
this.play();
}, false);
$.getJSON("scripts/data", function(data) {
var html = [];
/* loop through array */
$.each(data, function(index, g) {
$(".container").append(
"<div class='g-details'><div class='name'>" +
g.name + "</div>);
// And finally my click call is here
$(".g-contain").click(function() {
audioElement.play();
});
不确定为什么单击 g-contain
div 时 mp3 文件继续播放
最佳答案
这是由于这段代码:
audioElement.addEventListener('ended', function() {
this.play();
}, false);
您将事件监听器附加到音频元素,以便在播放结束
时重新播放
。因此,一旦播放(通过点击),它将无限播放。
ended
The ended event is fired when playback or streaming has stopped because the end of the media was reached or because no further data is available.
只需删除此代码即可。
关于javascript - 如何使用 JQuery 使音频仅播放一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44731915/