事件绑定方式对比

<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <tilte></tilte>
  <style>
    #odiv ul{
      width: 300px;
      height: 500px;
      background-color: blueviolet;
    }
  </style>
</head>
<body>
  <input type="text" id="text" />
  <input type="button" value="添加" id="btn" />
  <div id="odiv">
    <ul></ul>
  </div>
<script>
    window.onload = function() {
      var obtn = document.getElementById('btn');
      var otext = document.getElementById('text');
      var odiv = document.getElementById('odiv');
      var oul = odiv.getElementsByTagName('ul')[0];
      obtn.onclick = function() {
        var li = document.createElement('li');
        var lis= oul.getElementsByTagName('li');
        li.innerHTML = otext.value + '<a href="javascript:;">删除</a>';
        if (lis.length > 0) {
          oul.insertBefore(li, lis[0]);
        } else {
          oul.appendChild(li);
        }
        var oa = oul.getElementsByTagName('a');
        for(var i=0; i<oa.length;i++){
          oa[i].onclick = function(){
            oul.removeChild(this.parentNode);
          }
        }
      }
    }

</script>
</body>
</html>

  

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<tilte></tilte>
<script>
    window.addEventListener('load', function(){
        var ul = document.getElementsByTagName('ul')[0]
            ,text = document.getElementById('otex')
        document.getElementById('odin').addEventListener('click', function (e) {
            var li = document.createElement('li')
            li.innerHTML =  text.value + '<a href="javascript:;">删除</a>'
            ul.appendChild(li)
        })
        ul.addEventListener('click', function (e) {
            if(e.target && e.target.nodeName == 'A')
            ul.removeChild(e.target.parentNode)
        })
    })
</script>
<style>
    #odiv_1 ul{
      width: 300px;
      height: 500px;
      background-color: blueviolet;
    }
</style>
</head>
<body>
    <input type="text" value="" id="otex" />
    <input type="button" value="添加" id="odin" />
    <div id="odiv_1">
        <ul></ul>
    </div>
</body>
</html>

  

posted @ 2017-10-24 14:49  learn_by_doing  阅读(106)  评论(0编辑  收藏  举报