JavaScript DOM 动态创建标记
注意:避免使用document.write() 没有将结构和行为分开 createElement createTextNode创建元素 insertBefore 是将指定元素插入目标元素的前面 需要 父元素 属性 parentNode就可以得到父元素 insertBefore: var gallery=document.getElementById("sdf"); gallery.insertBefore(new,gallery);gallery insertAfter: 需要自己编写 挺有用的 function insertAfter(new,old){ var parent=old.parentNode; if(parent.lastChild==old){ parent.appendChild(new); }else{ old.insertBefore(new,old.nextSibling); } } innerHTML的使用: var test=document.getElementById("tes"); test.innerHTML="<p>inserted <em>this</em> content.</p>"; 显示的值是inserted this content. 注意:DOM方法如 setAttribute 方法并未改变文档的物理内容 如果用文本编辑器而不是浏览器去打开的话 根本看不到变化 因为浏览器实际显示的是那颗DOM节点树 在浏览器看来DOM节点树才是文档 所以 动态创建标记并不是创建标记 而是改变DOM节点树。 创建元素:var para=document.createElement("p"); 一般创建出来就赋值给一个变量 var para=document.createElement("p"); var testdiv=document.getElementById("testDiv"); testdiv.appendChild(para); 和 testdiv.appendChild(document.createElement("p")); 创建文本元素: var para=document.createElement("p"); var testdiv=document.getElementById("testdiv"); var testdiv.appendChild(para); var txt=document.createTextNode("hello world"); para.appendChild(txt); 如果创建 更复杂的组合呢? 如 <p>this is <em>my</em> content.</p> function(){ var txt1=document.createTextNode("this is "); var emx=document.createElement("em"); var txt2=document.createTextNode("my"); var txt3=document.createTextNode("content."); var para=document.createElement("p"); para.appendChild(txt1); para.appendChild(emx); emx.appendChild(txt2); para.appendChild(txt3);vv var textdiv=document.getElementById("divTe"); testdiv.appendChild(para); } 重回图片库 : html中的一个图片和文字仅仅是为了showPic服务 这些元素的存在只是为了让DOMD来处理他们呢 那么只能用DOM的方法来创建他们就好了 var placeholder=document.createElement("img"); placeholder.setAttribute("src","xx.gif"); placeholder.setAttribute("id","sdf"); var decription=document.createElement("p"); decription.setAttribute("id","zzz"); var desctext=document.createTextNode("choose an image"); decription.appendChild(desctext); 可以直接最佳到body元素节点后面 document.getElementByTagName("body")[0].appendChild(placeholder); document.getElementByTagName("body")[0].appendChild(decription); 也可以用HTML-DOM document.body.appendChild(placeholder); document.body.appendChild(decription); 最后图片库改进后的结果是: function insertAfter(new,old){ var parent=old.parentNode; if(parent.lastChild==old){ parent.appendChild(new); }else{ old.insertBefore(new,old.nextSibling); } } function prepare(){ if(!document.createElement) return false; if(!document.createTextNode) return false; if(!document.getElementById) return false; if(!document.getElementById("imagegallery")) return false; var placeholder=document.createElement("img"); placeholder.setAttribute("src","xx.gif"); placeholder.setAttribute("id","sdf"); var decription=document.createElement("p"); decription.setAttribute("id","zzz"); var desctext=document.createTextNode("choose an image"); decription.appendChild(desctext); var gallery=document.getElementById("imageallery"); insertAfter(placeholder,gallery); insertAfter(decription,placeholder); }