我必须按照api的json长度追加这些元素。但我是createDocumentFragment的新手,所以我不知道该怎么做。下面的HTML代码是我必须多次附加的,以及示例js代码。
<div class="column is-3 vid">
<div class="panel">
<p class="is-marginless"><img src="imgSrc"/></p>
<div class="panel vidInfo"><a href="#" class="vid-title"><span>text</span></a>
<div class="columns has-text-centered">
<div class="column">
<div class="panel-item reddit-ups"><i class="fa fa-reddit-alien fa-2x"></i>2 </div>
<div class="panel-item reddit-date"><i class="fa fa-calendar fa-2x"></i>2d </div>
</div>
</div>
</div>
</div>
</div>
js代码
var fragment = document.createDocumentFragment();
for(var i=0; i<20; i++){
//append elements like html code above in body.
}
答案 0 :(得分:0)
您可以将现有的html
置于<script>
元素的document
元素中,type
设置为text/html
,然后调用获取.innerHTML
对于元素,使用.insertAdjacentHTML()
和"beforeend"
作为第一个参数,将html
字符串追加到document.body
。
<!DOCTYPE html>
<html>
<head>
<script id="template" type="text/html">
<div class="column is-3 vid">
<div class="panel">
<p class="is-marginless"><img src="imgSrc" /></p>
<div class="panel vidInfo"><a href="#" class="vid-title"><span>text</span></a>
<div class="columns has-text-centered">
<div class="column">
<div class="panel-item reddit-ups"><i class="fa fa-reddit-alien fa-2x"></i>2 </div>
<div class="panel-item reddit-date"><i class="fa fa-calendar fa-2x"></i>2d </div>
</div>
</div>
</div>
</div>
</div>
</script>
</head>
<body>
<script>
var template = document.getElementById("template");
var html = template.innerHTML;
for (var i = 0; i < 20; i++) {
//append elements like html code above in body.
document.body.insertAdjacentHTML("beforeend", html);
}
</script>
</body>
</html>