javascript 事件代理,冒泡与捕获,target与currentTarget

in JavaScript with 0 comment

javascript 事件

<!DOCTYPE html>
<html>
<head>
    <title>事件代理</title>

</head>
<body>
  <style>
    ul>li{
      color: red;
    }
    .outer{
      width: 300px;
      height: 300px;
      background-color: red;
    }
    .outer .middle {
      width:200px;
      height: 200px;
      background-color: green;
    }
    .outer .middle .inner {
      width: 100px;
      height: 100px;
      background-color: yellow;
    }
  </style>
  <h1>冒泡排序</h1>
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
  </ul>

  <div class="outer">outer
    <div class="middle">middle
      <div class="inner">
        inner
      </div>
    </div>
  </div>
  <script type="text/javascript">
    //js事件代理:原理就是事件冒泡
    //需求是ul下1000个li, 给每个li绑定事件,点击时输出当前li的innerHTML
    let ul = document.getElementsByTagName('ul')[0]
    ul.addEventListener('click', function(e) {
      e = e||window.event
      let target = e.target || e.srcElement
      if(target.tagName.toLowerCase() === 'li'){//tagName === nodeName
        console.log(target.innerHTML)
      }
    }, true)


 //js事件冒泡与事件捕获,addEventListener第三个参数默认false,即用冒泡模式,如果为true,则为捕获模式
 /*
   let outer = document.getElementsByClassName('outer')[0]
   outer.addEventListener('click', function(e) {
    //用于停止冒泡
    e.stopPropagation()
    console.log('outer ' + e.target.className)
   }, false)

   let middle = document.getElementsByClassName('middle')[0]
   middle.addEventListener('click', function(e) {
    //e.stopPropagation()
    console.log('middle ' + e.target.className)
   }, false)

   let inner = document.getElementsByClassName('inner')[0]
   inner.addEventListener('click', function(e) {
    e.stopPropagation()
    console.log('inner ' + e.target.className)
   }, false)

   */

   //target与currentTarget
   let outer = document.getElementsByClassName('outer')[0]
   outer.addEventListener('click', function(e) {
    console.log('outer ' + e.currentTarget.className)
    console.log('outer ' + e.target.className)
   }, false)
   
   // let inner = document.getElementsByClassName('inner')[0]
   // inner.addEventListener('click', function(e) {
   //  console.log('inner ' + e.currentTarget.className)
   //  console.log('inner ' + e.target.className)
   // }, false)



  </script>
</body>
</html>
评论已关闭.