简体   繁体   中英

audio.play() working within existing function but not as lone function

I am trying to make a sound play when a button is clicked. Here is the function that I am trying to use:

function sound(){

  var audio = new Audio("button.wav");
  audio.play();

}

and then I have this at the bottom of the file:

document.getElementById("convert").onclick = function() { sound(); };

I know that the code works because if I put the 2 lines of code inside the sound function inside of another function that performs a calculation on the button click, the sound plays. Why is the code only working when added to an existing function, but not as its own?

I'm assuming that by "its own" you are referring to this:

document.getElementById("convert").onclick = sound();

In this case, you are assigning the returned value of sound() to the onclick property of the element. If you want sound to be called when the button is clicked, remove the parenthesis:

document.getElementById("convert").onclick = sound;

Demo:

 function sound(){ var audio = new Audio("https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"); audio.play(); } document.getElementById("convert").onclick = sound;
 <button id="convert">Play</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM