为什么我的JS函数不能与按钮一起使用?

时间:2019-03-05 19:16:19

标签: javascript

HTML

                <audio id="song" controls> <source src="song.mp3"></source>
                </audio>
                <button class="controls" id="play">Play</button>

JavaScript

            var play = document.getElementById("song");
            song.addEventListener ("click", buttonActions);
            function buttonActions(event){
                song.play();
            }

1 个答案:

答案 0 :(得分:3)

您正在将事件处理程序附加到<audio>元素,而不是<button>元素。

代替:

var play = document.getElementById("song");
song.addEventListener ("click", buttonActions);    
function buttonActions(event){
    song.play();
}

应该是:

var play = document.getElementById("play");
play.addEventListener ("click", buttonActions);    
function buttonActions(event){
    var song = document.getElementById("song");
    song.play();
}