多个按钮的一个脚本

时间:2016-05-20 16:52:39

标签: javascript

我在工作中使用的音板来惹恼同事。它有多个按钮,播放或停止声音。现在每个按钮都有自己的脚本来播放声音。所以我在页面上最多有47个声音,并且必须为每个声音编写这个脚本。我想要清理它并拥有一个适用于所有这些的智能脚本。 我的按钮看起来像:

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

然后我有音频元素的定义:

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

和脚本:

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

所以在我看来,如果我能定义声音1&#39;在按下每个按钮时,相同的脚本应该适用于每个按钮。正如我现在所知,我必须定义&#39; sound1&#39; &#39; SOUND2&#39; &#39; sound3&#39;依此类推,并指出一个新的“切换声”&#39;在他们每个人。

3 个答案:

答案 0 :(得分:1)

你可以重写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;
}

然后使用它,你可以将数字传递给函数:

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

答案 1 :(得分:1)

我不确定如何鼓励这一点,但是......

<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>

答案 2 :(得分:0)

更好的方法是使用事件委托,并将事件处理程序放在更高的位置

<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();
}