【问题标题】:Getting id from a specific button clicked?从单击的特定按钮获取ID?
【发布时间】:2021-08-13 08:28:11
【问题描述】:

完全初学者问题就在这里。一个月前开始学习前端开发,现在我已经接触了 Javascript,开始着手我的第一个实践项目。在这种情况下,我想创建一个非常简单的吉他调音器,您可以在其中单击一个按钮并执行其对应的字符串。

这是我到目前为止得到的,但无法表达如何获取点击按钮的 id。而且,不知道如何在单击另一个按钮时结束一个音符的循环

const keyS = document.addEventListener('keydown', function(e){
    (e.key === 'd') ? this.getElementById ("string6").play()
   :(e.key === 'f') ? this.getElementById ("string5").play()
   :(e.key === 'g') ? this.getElementById ("string4").play()
   :(e.key === 'j') ? this.getElementById ("string3").play()
   :(e.key === 'k') ? this.getElementById ("string2").play()
   :(e.key === 'l') ? this.getElementById ("string1").play()
   : alert("That's not a valid key!")
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles/main.css">
    <title>Guitar Tuner</title>
    <script src="scripts/main.js"></script>
</head>
<body>
    <ul>
        <li><audio id="string" src="sounds/string6.mp3" type="audio/mpeg" controls loop></audio></li>
        <li><audio id="string5" src="sounds/string5.mp3" type="audio/mpeg" controls loop></audio></li>
        <li><audio id="string4" src="sounds/string4.mp3" type="audio/mpeg" controls loop></audio></li>
        <li><audio id="string3" src="sounds/string3.mp3" type="audio/mpeg" controls loop></audio></li>
        <li><audio id="string2" src="sounds/string2.mp3" type="audio/mpeg" controls loop></audio></li>
       <li><audio id="string1" src="sounds/string1.mp3" type="audio/mpeg" controls loop></audio></li>
       <br>
        <button onclick="clickNote()">6th String</button>
        <button onclick="clickNote()">5th String</button>
        <button onclick="clickNote()">4th String</button>
        <button onclick="clickNote()">3rd String</button>
        <button onclick="clickNote()">2nd String</button>
        <button onclick="clickNote()">1st String</button>
  </ul>

</body>
</html>

我知道这可能是一个非常愚蠢的问题,但我想了解它是如何正常工作的,然后开始摆弄它。

提前感谢大家,非常欢迎任何 JS 学习或前端职业发展技巧!

P.S:请您原谅任何语法错误,因为英语不是我的母语。

【问题讨论】:

  • 您需要在按钮单击时播放正确的声音吗?如果我点击 d f j g k l 按钮点击声音播放
  • 关于如何获取被点击元素的id - stackoverflow.com/q/30786154/853295
  • 拥有一个音频元素并使用该元素播放所有声音可能会更简单。您可以根据按下的按钮设置其来源。停止它很容易,因为您只需播放下一个声音,它就会停止前一个声音。
  • 您还可以将参数传递给您的clickNote() 函数。可能是注释,例如clickNote("a") 或索引,例如clickNote(1)。在您的 html 中,只需使用所需的参数调用函数,例如&lt;button onclick="clickNote('a')"&gt;。只要您正确填充值,这将告诉您单击了哪个按钮。
  • How to get the id of the clicked button。从您的代码来看,虽然看起来您正在使用按键 - here's how to detect which key was pressed

标签: javascript html


【解决方案1】:

正如 Paul 在他的 cmets 中提到的,使用一个 audio 控件,然后让您的按钮更新它。此示例在每个按钮上使用data attributes 来标识字符串,并将按钮包装在一个容器中,并使用event delegation 来捕获按钮事件,因为它们会在 DOM 中冒泡,因此每个按钮上都没有侦听器。

// Caching the audio and container elements
const audio = document.querySelector('audio');
const buttons = document.querySelector('#buttons');

// Adding an event listener to the button container only
buttons.addEventListener('click', handleClick, false);

function handleClick(e) {

   // Grab the id from the data attribute
  const { target: { dataset: { id } } } = e;

  // There is not .stop() method, so we need to pause
  // the audio, and then reset the timer
  audio.pause();
  audio.currentTime = 0;

  console.log(`Play ${id} string`);

  // An example
  audio.src = 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/123941/Yodel_Sound_Effect.mp3';

  // Your code will look like this
  // audio.src = `sounds/string${id}.mp3`;
  audio.play();
}
<audio type="audio/mp3" controls loop /></audio>
<div id="buttons">
  <button data-id="6">6th String</button>
  <button data-id="5">5th String</button>
  <button data-id="4">4th String</button>
  <button data-id="3">3rd String</button>
  <button data-id="2">2nd String</button>
  <button data-id="1">1st String</button>
</div>

其他文档

【讨论】:

    【解决方案2】:

    简短的一般回答:

    可以使用this获取元素+属性,比如:

    function doit(obj) {
      alert(obj.id)
    }
    &lt;button id="me" onclick="doit(this)"&gt;test of ME&lt;/button&gt;

    或者如果它可以像这样聚焦:

    function doit() {
      var obj=document.activeElement;
      alert(obj.id);
    }
    &lt;button id="me" onclick="doit()"&gt;test of ME&lt;/button&gt;

    或者如果你像这样使用EventListener

    document.getElementById('me').addEventListener('click',doit);
    
    function doit() {
      alert(this.id);
    }
    &lt;button id="me"&gt;test of ME&lt;/button&gt;

    你的确切答案+想法:

    我们最好使用attribute 来检测它是哪个键,因为我们可以对所有人使用通用函数。像这样:

    // For being sure that all elements load, we have to set EventListeners when DOMContentLoaded:
    window.addEventListener('DOMContentLoaded', function(e) {
        
        document.querySelectorAll('button[note]') // Get all buttons that have note as attributes
        
          .forEach(function(obj){  // For each of them
          
            obj.addEventListener('click',playnote); // Set playnote function for on click
            
          });
        
        
    });
    
    // Also the general keydown event listener:
    window.addEventListener('keydown',playnote);
    
    // Where we decied to play the note:
    function playnote(e) { // e will be Event
    
      var note; // Defining note variable for local use
      
      if (e.type=='click') { // Checking the event is clicking on button
      
        note=this.getAttribute('note'); // Getting the note attribute
        
      } else { // Or else is a keydown
      
        note=e.key; // Getting the key
        
      }
      
      console.log(note); // Just debugging what note it got (You have to remove it later)
      
      note=document.querySelector('audio[note="'+note+'"]'); // Find the audio element by it "note" attribute
      
      if (note) note.play(); // Play if the element exist
      
    }
    <audio note="a" src="sounds/a.mp3" type="audio/mpeg" controls></audio><br>
    <audio note="b" src="sounds/b.mp3" type="audio/mpeg" controls></audio><br>
    <audio note="c" src="sounds/c.mp3" type="audio/mpeg" controls></audio><br>
    <br>
    <button note="a">A</button><br>
    <button note="b">B</button><br>
    <button note="c">C</button><br>

    注意(1):如果您不需要看到音频元素,则必须立即更改playnote函数和create an audio element

    注意 (2): 如果源是文件,音频元素有时会延迟播放。因此,如果您需要快速播放,我建议您使用Data URI 作为来源。

    关于您询问的循环: https://www.w3schools.com/html/html5_audio.asp https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/loop

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      • 2017-06-27
      • 2018-01-25
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      相关资源
      最近更新 更多