一个理解js动态创建节点并注册事件及传递参数的例子

来源:互联网 发布:python interfaceerror 编辑:程序博客网 时间:2024/05/18 03:20
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head>    <title>无标题页</title>  </head><body><input type="button" value="动态创建"  onclick="CreateDom();"/> <div id="abc">   </div>     <input id="Text1" style="width: 777px; height: 33px" type="text" />    <br />    <input id="Button2" type="button" value="button" onclick="return Button2_onclick()" /></body></html>  <script type="text/javascript">   var count =1;   var obj =new Object;    function CreateDom(){    var id ="but"+count;  var el = document.createElement("input");el.type="button";el.value="点击我";el.setAttribute("id",id);el.setAttribute("name","点击我呀");el.setAttribute("value","后来添加的");//el.elements.item[0].value ="点击我"//el.createTextNode("点击我");//el.setAttribute("value","点击我"); //obj.ff=fuc1(count); obj.ff=fuc1(count);     document.getElementById("abc").appendChild(el);if(window.attachEvent){el.attachEvent("onclick",obj.ff,obj);}else{    el.addEventListener("click",obj.ff,false);}count ++;    } function fuc1(i) {return function(){         var id ="but"+i;alert(id);}//alert(document.getElementById(id).value); }    </script>