用JavaScript插入HTML元素 [英] Inserting HTML elements with JavaScript

查看:130
本文介绍了用JavaScript插入HTML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下语法时,不要繁琐地搜索每种类型的属性和事件的解决方法:

  elem = document。的createElement( DIV); 
elem.id ='myID';
elem.innerHTML ='my Text'
document.body.insertBefore(elem,document.body.childNodes [0]);

有没有一种方法可以将整个HTML元素声明为一个字符串?例如:

  elem = document.createElement(< div id ='myID'> my Text< / div> ); 
document.body.insertBefore(elem,document.body.childNodes [0]);


解决方案

$ c> innerHTML 创建一个片段然后插入它可能会更好:

  function create(htmlStr){
var frag = document.createDocumentFragment(),
temp = document.createElement('div');
temp.innerHTML = htmlStr;
while(temp.firstChild){
frag.appendChild(temp.firstChild);
}
return frag;
}

var fragment = create('< div> Hello!< / div>< p> ...< / p>');
//您可以使用本地DOM方法插入片段:
document.body.insertBefore(fragment,document.body.childNodes [0]);

好处:


  1. 您可以使用本地DOM方法进行插入,例如insertBefore,appendChild等。

  2. 您可以在插入实际DOM节点之前访问它们;您可以访问该片段的childNodes对象。

  3. 使用文档片段非常快速;比在DOM之外创建元素更快,并且在某些情况下比innerHTML更快。






尽管在函数中使用 innerHTML ,但它都发生在DOM之外,因此它比您想象的要快得多... p>

Instead of tediously search for workarounds for each type of attribute and event when using the following syntax:

   elem = document.createElement("div");
   elem.id = 'myID';
   elem.innerHTML = ' my Text '
   document.body.insertBefore(elem,document.body.childNodes[0]);

Is there a way where I can just declare the entire HTML element as a string? like:

  elem = document.createElement("<div id='myID'> my Text </div>");
  document.body.insertBefore(elem,document.body.childNodes[0]);

解决方案

Instead of directly messing with innerHTML it might be better to create a fragment and then insert that:

function create(htmlStr) {
    var frag = document.createDocumentFragment(),
        temp = document.createElement('div');
    temp.innerHTML = htmlStr;
    while (temp.firstChild) {
        frag.appendChild(temp.firstChild);
    }
    return frag;
}

var fragment = create('<div>Hello!</div><p>...</p>');
// You can use native DOM methods to insert the fragment:
document.body.insertBefore(fragment, document.body.childNodes[0]);

Benefits:

  1. You can use native DOM methods for insertion such as insertBefore, appendChild etc.
  2. You have access to the actual DOM nodes before they're inserted; you can access the fragment's childNodes object.
  3. Using document fragments is very quick; faster than creating elements outside of the DOM and in certain situations faster than innerHTML.


Even though innerHTML is used within the function, it's all happening outside of the DOM so it's much faster than you'd think...

这篇关于用JavaScript插入HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆