将任意HTML插入DocumentFragment [英] Inserting arbitrary HTML into a DocumentFragment

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

问题描述

我知道 innerHTML 添加到文档片段最近已经讨论过,希望能够纳入DOM标准。但是,在此期间您应该使用的解决方法是什么?

I know that adding innerHTML to document fragments has been recently discussed, and will hopefully see inclusion in the DOM Standard. But, what is the workaround you're supposed to use in the meantime?

即,

var html = '<div>x</div><span>y</span>';
var frag = document.createDocumentFragment();

我想要 div span frag 内,有一个简单的单行。

I want both the div and the span inside of frag, with an easy one-liner.

没有循环的奖励积分。允许jQuery,但我已经尝试过 $(html).appendTo(frag);之后 frag 仍然是空的。

Bonus points for no loops. jQuery is allowed, but I've already tried $(html).appendTo(frag); frag is still empty afterward.

推荐答案

这是一种方式a href =http://caniuse.com/template>现代浏览器没有循环:

Here is a way in modern browsers without looping:

var temp = document.createElement('template');
temp.innerHTML = '<div>x</div><span>y</span>';

var frag = temp.content;

或作为可重复使用的

function fragmentFromString(strHTML) {
    var temp = document.createElement('template');
    temp.innerHTML = strHTML;
    return temp.content;
}

更新:
我找到了一种更简单的方式来使用Pete的主要想法,它将IE11添加到组合中:

UPDATE: I found a simpler way to use Pete's main idea, which adds IE11 to the mix:

function fragmentFromString(strHTML) {
    return document.createRange().createContextualFragment(strHTML);
}

保险范围优于< template> 方法并在IE11,Ch,FF中测试好。

The coverage is better than the <template> method and tested ok in IE11, Ch, FF.

可用的实时测试/演示http://pagedemos.com/str2fragment/

Live test/demo available http://pagedemos.com/str2fragment/

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

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