为不同的按钮添加不同的声音

问题描述 投票:0回答:2

我正在使用 Javascript 和 jQuery 完成一个项目。这些项目要求我为按钮添加声音。根据我单击的按钮,应该会播放不同的声音。我知道如何将单个音频文件添加到按钮,但有人可以帮我为每个按钮添加不同的音频吗?

$(".btn").on("click" , function () {
    let buttonSound = $(this).attr("id");
    playSound(buttonSound);

});

我的项目给了一个随机颜色,对应一个按钮。这段代码可以播放那个按钮的声音,但它也会用我的其他按钮播放那个声音(而不是它们应该播放的声音)。改变声音的唯一方法是刷新屏幕,但这有同样的问题,只是使用不同的随机按钮。任何帮助将不胜感激。

javascript jquery eventhandler
2个回答
2
投票

.btn
确实是一个太常见的选择器来做一些特定的事情。
相反,您可以尝试这种更好的策略,那就是使用
data-*
属性
,例如:

<button class="btn" data-sound="cat" type="button">Cat</button>
<button class="btn" data-sound="dog" type="button">Dog</button>

然后在 jQuery 中:

$("[data-sound]").on("click", function() {
  const buttonSound = $(this).data("sound");
  playSound(buttonSound);
});

如果您愿意,也可以使用纯 JavaScript:

document.querySelectorAll("[data-sound]").forEach((elBtn) => {
  elBtn.addEventListener("click", () => {
    playSound(elBtn.dataset.sound);
  });
});

这样您就可以摆脱 ID 选择器,如果需要,您可以拥有多个播放相同声音的按钮 - 而不会遇到与重复 ID 相关的问题。
需要在 HTML 中存储和检索任意数据时,始终使用 data 属性


-1
投票

根据您的原始查询,您似乎正在进行一个随机选择按钮颜色的项目,并且您希望为每个按钮播放不同的声音。但是当您尝试播放所选按钮的声音时,它会同时播放其他按钮的声音。您可以使用以下示例代码来解决此问题:

<button id="button1" class="color-button" data-sound="sound1.mp3">Button 1</button>
<button id="button2" class="color-button" data-sound="sound2.mp3">Button 2</button>
<button id="button3" class="color-button" data-sound="sound3.mp3">Button 3</button>
<button id="button4" class="color-button" data-sound="sound4.mp3">Button 4</button>

<script>
  // Get a reference to each button
  const button1 = document.querySelector('#button1');
  const button2 = document.querySelector('#button2');
  const button3 = document.querySelector('#button3');
  const button4 = document.querySelector('#button4');

  // Add an event listener to each button
  button1.addEventListener('click', () => {
    playSound('sound1.mp3');
  });

  button2.addEventListener('click', () => {
    playSound('sound2.mp3');
  });

  button3.addEventListener('click', () => {
    playSound('sound3.mp3');
  });

  button4.addEventListener('click', () => {
    playSound('sound4.mp3');
  });

  // Function to play a sound based on its filename
  function playSound(soundFilename) {
    // Create a new audio element for the sound
    const sound = new Audio(soundFilename);
    
    // Play the sound
    sound.currentTime = 0;
    sound.play();
  }

  // Generate a random number between 1 and 4
  const randomNumber = Math.floor(Math.random() * 4) + 1;

  // Get the button that corresponds to the random number
  const randomButton = document.querySelector(`#button${randomNumber}`);

  // Get the sound filename for the random button
  const soundFilename = randomButton.getAttribute('data-sound');

  // Simulate a click on the random button to play its sound
  randomButton.click();
</script>
© www.soinside.com 2019 - 2024. All rights reserved.