插入HTML內容與文本內容以前用的是innerHTML與innerText方法,今天微博上看到《JavaScript insertAdjacentHTML?and?beforeend》這篇文章,重新勾起對insertAdjacentHTML和 insertAdjacentText方法回憶,以前網上有個比較靠譜的兼容方法:
/** * @param {HTMLElement} el * @param {String} where beforeBegin、afterBegin、beforeEnd、afterEnd * @param {String} html */ function insertHTML(el, where, html) { if (!el) { return false; } where = where.toLowerCase(); if (el.insertAdjacentHTML) {//IE el.insertAdjacentHTML(where, html); } else { var range = el.ownerDocument.createRange(), frag = null; switch (where) { case "beforebegin": range.setStartBefore(el); frag = range.createContextualFragment(html); el.parentNode.insertBefore(frag, el); return el.previousSibling; case "afterbegin": if (el.firstChild) { range.setStartBefore(el.firstChild); frag = range.createContextualFragment(html); el.insertBefore(frag, el.firstChild); } else { el.innerHTML = html; } return el.firstChild; case "beforeend": if (el.lastChild) { range.setStartAfter(el.lastChild); frag = range.createContextualFragment(html); el.appendChild(frag); } else { el.innerHTML = html; } return el.lastChild; case "afterend": range.setStartAfter(el); frag = range.createContextualFragment(html); el.parentNode.insertBefore(frag, el.nextSibling); return el.nextSibling; } } }
在還沒開始用jQuery之前,一直用這個方法。當然后來用了jQuery的.append(),.appendTo(),.html(),.prepend(),.prependTo(),.text(),.after(),.before(),.insertAfter(),.insertBefore()也很方便。
insertAdjacentHTML和 insertAdjacentText這兩個方法很靈活,可以在指定的地方插入html內容和文本內容,在大部分情況下比element.innerHTML的性能更好,比Document Fragments更好的HTML文檔插入方案,因為我們知道Document Fragments在某些IE版本中的表現不好。
insertAdjacentText方法與 insertAdjacentHTML方法類似,只不過只能插入純文本,參數相同。
MDN上查了一下兼容性:http://www.css88.com/archives/https://developer.mozilla.org/en-US/docs/Web/API/element.insertAdjacentHTML
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|
Basic support | 1.0 | 8.0 (8.0) | 4.0 | 7.0 | 4.0 (527) |
接口也很簡單:
element.insertAdjacentHTML(position, text);
需要傳入字符串參數position
,以及字符串參數html
代碼。我們可以對照jQuery的HTML插入方法。
參數position
的取值:
- beforeBegin:在該元素前插入
- afterBegin:在該元素第一個子元素前插入
- beforeEnd:在該元素最后一個子元素后面插入
- afterEnd:在該元素后插入
方法同意支持空元素,和innerHTML與innerText方法沒什么區別了。
性能測試可以看這里:http://jsperf.com/innerhtml-vs-insertadjacenthtml-vs-dom/8