动态插入和静态代码获得方式都是一样的。 var p = document.createElement("p"); p.setAttribute("id","test"); var t = document.createTextNode("hello"); p.appendChild(t); document.getElementById("main").appendChild(p); alert(document.getElementById('test')); http://jsfiddle.net/bsbwestlife/nABQ6/
创建元素的时候就给这个元素添加个事件,如: var div = document.createElement("div"); div.id = "div1"; div.className = "class1"; div.onclick = function(){ alert(this.id); alert(this.className); }
<div id="p"></div> <script type="text/javascript"> var div = document.createElement("div"); div.id = "div1"; div.className = "class1"; div.innerHTML = "My is append div"; div.onclick = function(){ alert(this.id); alert(this.className); } document.getElementById("p").appendChild(div); </script> 楼主可以试一试这个效果看看是不是你要求的
这个abc不就是你插入的东西了吗?
var p = document.createElement("p");
p.setAttribute("id","test");
var t = document.createTextNode("hello");
p.appendChild(t);
document.getElementById("main").appendChild(p);
alert(document.getElementById('test'));
http://jsfiddle.net/bsbwestlife/nABQ6/
var div = document.createElement("div");
div.id = "div1";
div.className = "class1";
div.onclick = function(){
alert(this.id);
alert(this.className);
}
<script type="text/javascript">
var div = document.createElement("div");
div.id = "div1";
div.className = "class1";
div.innerHTML = "My is append div";
div.onclick = function(){
alert(this.id);
alert(this.className);
}
document.getElementById("p").appendChild(div);
</script>
楼主可以试一试这个效果看看是不是你要求的