简体   繁体   English

使用JavaScript(appendChild)将新元素添加到DOM中

[英]Adding new elements into DOM using JavaScript (appendChild)

I sometimes need to add elements (such as a new link and image) to an existing HTML page, but I only have access to a small portion of the page far from where I need to insert elements. 我有时需要向现有的HTML页面添加元素(例如新的链接和图像),但我只能访问远离我需要插入元素的页面的一小部分。 I want to use DOM based JavaScript techniques, and I must avoid using document.write(). 我想使用基于DOM的JavaScript技术,我必须避免使用document.write()。

Thus far, I've been using something like this: 到目前为止,我一直在使用这样的东西:

//  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);

Is there a more efficient way that I could use to accomplish the same thing? 有没有更有效的方法可以用来完成同样的事情? It all seems necessary, but I'd like to know if there's a better way I could be doing this. 这一切似乎都是必要的,但我想知道是否有更好的方法可以做到这一点。

There is a more efficient way, and seems to be using documentFragments if possible. 有一种更有效的方法,如果可能的话似乎正在使用documentFragments。 Check it out: http://ejohn.org/blog/dom-documentfragments/ . 看看: http//ejohn.org/blog/dom-documentfragments/ Also this way should be less error prone and more maintainable than starting to mix up huge strings literals and setting them as innerHTML of some other DOM objects. 此外,这种方式应该比开始混合庞大的字符串文字并将它们设置为某些其他DOM对象的innerHTML更容易出错且更易于维护。

请注意, innerHTML既是非标准的,又是出了名的错误

Nothing wrong with that. 没有错。 Using innerHTML would be marginally faster and probably fewer characters but not noticeable for something of this scale, and my personal preference is for the more standard, uniformly supported and safer DOM methods and properties. 使用innerHTML会稍微快一些,可能会少一些字符,但对于这种规模的东西来说并不明显,我个人的偏好是更标准,统一支持和更安全的DOM方法和属性。

One minor point: the height and width properties of <img> elements should be numbers rather than strings. 一个小问题: <img>元素的heightwidth属性应该是数字而不是字符串。

If you're not adding many things, the way you've been doing it is ideal vs innerHTML. 如果你没有添加很多东西,你一直在做的方式与innerHTML相比是理想的。 If you're doing it frequently though, you might just create a generic function/object that takes the pertinent information as parameters and does the dirty work. 如果您经常这样做,您可能只是创建一个通用函数/对象,它将相关信息作为参数并进行脏操作。 IE IE

function addImage(src,width,height,alt,appendElem,href) {...}

I do this often in my own projects using prototyping to save time. 我经常在自己的项目中使用原型设计来节省时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM