事件绑定方式对比

吃可爱长大的小学妹 提交于 2020-01-08 03:49:17
<!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>

  

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!