简体   繁体   English

一个脚本用于多个按钮

[英]One Script for multiple buttons

I've got a soundboard I use at work to annoy coworkers. 我有一个用来在办公室打扰同事的音板。 It has multiple buttons, that play or stop a sound. 它具有多个按钮,可播放或停止声音。 Right now each button has its own script to play the sound. 现在,每个按钮都有其自己的脚本来播放声音。 So I'm up to 47 sounds on the page and have to write this script for each one. 因此,页面上我最多只能听到47个声音,因此必须为每个声音编写此脚本。 I'd like to clean that up and have a one smarter script that works for all of them. 我想清理它,并拥有一个更智能的脚本,适用于所有脚本。 my buttons look like: 我的按钮看起来像:

<button onclick="javascript:toggleSound1();">I don't know what we're yelling about.</button>

Then I have the definition of the audio element: 然后我有了音频元素的定义:

<audio id="sound1" src="sounds/dontknowwhatwereyellingabout.wav"></audio>

and the script: 和脚本:

<script type="text/javascript">
function toggleSound1() {
  var audioElem = document.getElementById('sound1');
  if (audioElem.paused)
    audioElem.play();
  else
    audioElem.pause(); audioElem.currentTime = 0;
}
</script>

So it seems to me that if i could define the 'sound1' on the press in each button the same script should work for each button. 因此在我看来,如果我可以在每个按钮上的按下按钮上定义“ sound1”,则相同的脚本应适用于每个按钮。 as I have it now I have to define 'sound1' 'sound2' 'sound3' and so on, and point a new 'togglesound' at each of them. 就像我现在拥有的那样,我必须定义“ sound1”,“ sound2”,“ sound3”,依此类推,并在每一个上指向一个新的“ togglesound”。

You could rewrite toggleSound1 to take an argument: 您可以重写toggleSound1以接受一个参数:

function toggleSound(num) {
  var audioElem = document.getElementById('sound' + num); // append the number to "sound" (sound1, sound2, etc.)
  if (audioElem.paused) {
    audioElem.play();
  } else {
    audioElem.pause();
  }
  audioElem.currentTime = 0;
}

Then to use it, you could just pass the number to the function: 然后使用它,您可以将数字传递给函数:

<button onclick="javascript:toggleSound(1);">I don't know what we're yelling about.</button>

I'm not sure how I feel about encouraging this, but... 我不确定如何鼓励这一点,但是...

<button onclick="toggleSound('sound1');">I don't know what we're yelling about.</button>
<button onclick="toggleSound('sound2');">Some other sound</button>

<script type="text/javascript">
function toggleSound1(soundId) {
  var audioElem = document.getElementById(soundId);
  if (audioElem.paused)
    audioElem.play();
  else
    audioElem.pause(); audioElem.currentTime = 0;
}
</script>

a better way is to use event delegation, and put the event handler higher up 更好的方法是使用事件委托,并将事件处理程序调高

<div onclick="handleAudio(e)">
  <button data-audio="1">I don't know what we're yelling about.</button>
  <button data-audio="2">Some other sound</button>
</div>

function handleAudio(e) {
  var audio = document.getElementById('sound' + e.target.dataset.audio);
  audio.play();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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