【发布时间】:2011-07-15 04:22:47
【问题描述】:
有时我需要向现有 HTML 页面添加元素(例如新链接和图像),但我只能访问远离我需要插入元素的页面的一小部分。我想使用基于 DOM 的 JavaScript 技术,我必须避免使用 document.write()。
到目前为止,我一直在使用这样的东西:
// Create new image element
var newImg = document.createElement("img");
newImg.src = "images/button.jpg";
newImg.height = "50";
newImg.width = "150";
newImg.alt = "Click Me";
// Create new link element
var newLink = document.createElement("a");
newLink.href = "/dir/signup.html";
// Append new image into new link
newLink.appendChild(newImg);
// Append new link (with image) into its destination on the page
document.getElementById("newLinkDestination").appendChild(newLink);
有没有更有效的方法可以用来完成同样的事情?这一切似乎都是必要的,但我想知道是否有更好的方法可以做到这一点。
【问题讨论】:
标签: javascript dom