我需要制作一份清单的副本,大约十个。该列表如下:
<nav>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
</nav>
如何在不编写代码10次的情况下进行x10复制?因为项目&#34; 1&#34;,&#34; 2&#34;等将链接相同的文件。
答案 0 :(得分:3)
var fragment = document.createDocumentFragment(),
ul = document.createElement('ul'),
li,
i;
for (i = 10; i--;) { //the way this loop works, will add the elements in reverse order. Order could be of importance to you, so just an FYI
li = document.createElement('li');
//do some stuff to li here
fragment.appendChild(li);
}
ul.appendChild(fragment);
没有JQuery,只有~10行
fragment
的参考:
https://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment
编辑
对于您希望按照我的理解迭代整个ul
而不是li
的情况:
var ul = document.createElement('ul'),
container = /*the container DOM element of the <ul>*/,
liFragment
ulFragment;
function create(tag, times) {
var fragment = document.createDocumentFragment(),
el;
for (times; times--;) {
el = document.createElement(tag);
//do some stuff to the element here
fragment.appendChild(el);
}
return fragment;
}
function clone(element, times, deep) {
var fragment = document.createDocumentFragment(),
deep = (typeof deep === 'boolean') ? deep : true;
el;
for (times; times--;) {
el = element.cloneNode(deep);
//do some stuff to the element here
fragment.appendChild(el);
}
return fragment;
}
liFragment = create('li', 10);
ul.appendChild(liFragment);
ulFragment = clone(ul, 10);
container.appendChild(ulFragment);
答案 1 :(得分:2)
这有效(jsFiddle):
的 HTML 强>:
<div id = "list">
<!-- to be populated using jquery-->
</div>
js :
var listContainer = $("#list")
for(i=0; i<10; ++i){
listContainer.append( $("<nav><ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> <li>8</li> <li>9</li> <li>10</li></ul>"))
console.log("adding...")
}
答案 2 :(得分:0)
你可以在jQuery中使用.clone()方法来做到这一点。
for (var i = 0; i < 9; i++) {
$('#target').append($('#copied').clone());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target">
<nav id="copied">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
</nav>
</div>