将keypress侦听器应用于所有子元素

时间:2014-11-20 03:53:35

标签: javascript keypress event-listener

假设我有一些看起来像这样的嵌套html元素:

<div class='container'>
  <p>content</p>
  <p>in enough different elements</p>
  <p>that making listeners</p>
  <p>for all of them</p>
  <p>would be a huge pain</p>
<div>

是否可以编写绑定到容器div的javascript侦听器,该容器div响应keyDown事件,而其任何子元素都处于焦点状态?

1 个答案:

答案 0 :(得分:0)

keydown事件支持事件冒泡,因此您只需将处理程序添加到container元素,如

document.querySelectorAll('.container')[0].addEventListener('keydown', function(e) {
  console.log('keypressed', this, e);
  //e.target will refer to the actual event target

  log('down in `' + e.target.innerHTML + '` with keycode: ' + (e.keyCode))
})

function log(msg) {
  document.querySelector('#log').innerHTML = msg;
}
<div class='container'>
  <p tabindex="1">content</p>
  <p tabindex="1">in enough different elements</p>
  <p tabindex="1">that making listeners</p>
  <p tabindex="1">for all of them</p>
  <p tabindex="1">would be a huge pain</p>
</div>
<div id="log"></div>