使用createDocumentFragment插入嵌套的div结构 [英] Inserting a nested div structure with createDocumentFragment

查看:216
本文介绍了使用createDocumentFragment插入嵌套的div结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用createDocumentFragment在一次命中创建七个嵌套的div元素?



我想创建一个包含A1,A2,A3和A4,然后A2a& A2b内A2。



注意:这是一个后续问题,这个,它解释了createDocumentFragment,但不是如何使用它来嵌套div。给出的答案如下(这是有帮助的):

  var fragment = document.createDocumentFragment(); 

函数u1(tag,id,className){
var tag = document.createElement(tag);
tag.id = id;
tag.className = className;
fragment.appendChild(tag);
}

//调用u1()七次

document.getElementById('foo')。appendChild(fragment);

有人可以解释如何嵌套?以上只是增加了七个孩子的foo。我拖网了,但是没有用。



谢谢。

解决方案>

而不是在片段上调用appendChild(在片段中创建顶级对象),您可以在片段中的其他对象之间调用appendChild,并嵌入到该对象中。这是一个伪代码示例,将tag2嵌套到标签中。

  var tag = document.createElement(tag); 
tag.id = id;
tag.className = className;
fragment.appendChild(tag);

var tag2 = document.createElement(tag);
tag2.id = id2;
tag.className = className2;
tag.appendChild(tag2);

注意:您还可以设置tag.innerHTML并创建一整套对象(包括多个图层根据您的需要嵌套)。


How do you use createDocumentFragment to create seven nested div elements in one hit?

I want to create a container A which contains A1, A2, A3 & A4, and then A2a & A2b within A2.

Note: this is a follow-up question to this which explained createDocumentFragment, but not how to nest divs using it. The answer given was as follows (which was helpful as far as it went):

var fragment = document.createDocumentFragment();

function u1(tag, id, className){
    var tag = document.createElement(tag);
    tag.id = id;
    tag.className = className;
    fragment.appendChild(tag); 
}

// call u1() seven times

document.getElementById('foo').appendChild(fragment);

Could someone explain how to nest? The above just adds seven children to 'foo'. I've trawled the web, but to no avail.

Thanks.

解决方案

Rather than calling appendChild on the fragment (which creates a top level object in your fragment), you call appendChild on one of the other objects in your fragment and that nests into that object. Here's a pseudo code example that puts tag2 nested into tag.

var tag = document.createElement(tag);
tag.id = id;
tag.className = className;
fragment.appendChild(tag); 

var tag2 = document.createElement(tag);
tag2.id = id2;
tag.className = className2;
tag.appendChild(tag2);

Note: you can also set tag.innerHTML and create a whole host of objects (including as many layers of nesting as you want) just from that HTML.

这篇关于使用createDocumentFragment插入嵌套的div结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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