单击存在多个类的位置时,获取标签的数据键

时间:2018-06-27 06:16:08

标签: javascript onclick alert

我想在单击时获取div的innerHTML 所有类名都相同的地方。

它适用于 A 文本,但是当单击S或D时不起作用。

<div class="keys">
     <div data-key="65" class="key">
      <kbd>A</kbd>
      <span class="sound">clap</span>
    </div>

    <div data-key="83" class="key">
      <kbd>S</kbd>
      <span class="sound">hihat</span>
    </div>

    <div data-key="68" class="key">
      <kbd>D</kbd>
      <span class="sound">kick</span>
    </div>
</div>

这是JavaScript代码

var x = document.querySelector('.key');
x.addEventListener('click', popUp);

function popUp(e) {
    alert(e.target.innerHTML);
}

2 个答案:

答案 0 :(得分:3)

querySelectorAll方法结合使用querySelector代替Array.from

由于querySelectorAll() 返回一个 NodeList ,因此您必须为每个项目附加一个click事件 handler

var x = Array.from(document.querySelectorAll('.key')).forEach(function(item){
   item.addEventListener('click', popUp);
});

function popUp(e) {
    alert(e.target.innerHTML);
}
<div class="keys">
     <div data-key="65" class="key">
      <kbd>A</kbd>
      <span class="sound">clap</span>
    </div>

    <div data-key="83" class="key">
      <kbd>S</kbd>
      <span class="sound">hihat</span>
    </div>

    <div data-key="68" class="key">
      <kbd>D</kbd>
      <span class="sound">kick</span>
    </div>
</div>

答案 1 :(得分:1)

向每个.key元素添加一个事件侦听器:

document.querySelectorAll('.key').forEach(key => {
  key.addEventListener('click', () => console.log(key.innerHTML));
});
<div class="keys">
     <div data-key="65" class="key">
      <kbd>A</kbd>
      <span class="sound">clap</span>
    </div>

    <div data-key="83" class="key">
      <kbd>S</kbd>
      <span class="sound">hihat</span>
    </div>

    <div data-key="68" class="key">
      <kbd>D</kbd>
      <span class="sound">kick</span>
    </div>
</div>

或者,而不是为每个key添加一个侦听器,通过事件委派,仅对.keys容器使用一个单个侦听器可能会更优雅,并从点击的元素中找到closest .key

document.querySelector('.keys').addEventListener('click', (e) => {
  const key = e.target.closest('.key');
  console.log(key.innerHTML);
});
<div class="keys">
  <div data-key="65" class="key">
    <kbd>A</kbd>
    <span class="sound">clap</span>
  </div>

  <div data-key="83" class="key">
    <kbd>S</kbd>
    <span class="sound">hihat</span>
  </div>

  <div data-key="68" class="key">
    <kbd>D</kbd>
    <span class="sound">kick</span>
  </div>
</div>