关于javascript中动态创建的节点怎么继续使用原方法。

  经常会在写代码的时候碰到一个问题,新创建的DOM节点不能像html中已经写好的节点一样使用已给定的样式,也不能使用已经给定的方法,我总结的几个方法如下:


1.最基本的解决方式是事件委托,将事件委托给它的父元素,然后在使用target指向目标元素;

    window.onload=function(){

      let ul=document.getElementsByTagName("ul");      

      let li=document.getElementsByTagName("li");

      ul.onclick=function(e){

        let evt=e || window.event;

        let target = evt.target || evt.srcElement;

        if(target.nodeName == "li"){

          alert("11111");

        }

      }

    }

这样无论是已经给定的 li 还是动态添加的 li 都可以点击弹出 11111 了。


2.在绑定方法时,直接在动态生成的DOM里添加上onclick方法;

HTML:ul.appendChild( `<li  onclick="fun(this)"></li>` ),使用了模板字符串;

JS:function fun(a){

    a.style.backgroundColor="red";

  }

这样新添加的 li 在点击时背景色会变红;


3.jquery方法:on( ),类似于事件委托,给父元素绑定事件点击子元素触发;

HTML:ul.appendChild( `<li></li>` ).

JS:$("ul").on("click" , "li" , function(){

    $("li").css("background","red");

  })

这样新添加的 li 在点击时背景色会变红;

猜你喜欢

转载自www.cnblogs.com/flower-y/p/10909981.html
今日推荐