我是javascript的新手,我想创建具有多个div和多个元素的div。请参阅下面的代码
<style>
.list-group li {
list-style: none;
}
.panel-info, .panel-rating, .panel-more1 {
float: left;
margin: 0 10px;
height: 60px;
}
.icon {
height: 30px;
width: 30px;
}
.header {
background-color: #f44336;
padding: 15px 20px;
color: white;
text-align: center;
}
</style>
<div id="listContainer">
<div>
<ul class="list-group">
<li>
<div class="panel-body panel panel-default" style="height: 70px;">
<div class="panel-info">
<p><strong>Shailendra Kushwah</strong></p>
</div>
<div class="panel-more1">
<img src="img/feestatus/cancel-button.png" class="icon" />
<br /><span>Installment 1</span>
</div>
<div class="panel-more1">
<img src="img/feestatus/cancel-button.png" class="icon" />
<br /><span>Installment 2</span>
</div>
<div class="panel-more1">
<img src="img/feestatus/cancel-button.png" class="icon" />
<br /><span>Installment 3</span>
</div>
</div>
</li>
</ul>
</div>
</div>
id="listContainer"
的元素。请帮助
答案 0 :(得分:2)
没有js,没有数组。但独立于所有这些,
如果要将元素添加到当前DOM结构中,
首先,您需要创建它。
var new_element = document.createElement('div')
//might be p, span, ol, li, a, section etc.
然后将它附加到任何你想要的地方。
var my_container = document.getElementById("my-container")
my_container.appendChild(new_element);
/*
* for most bottom of current dom node
* document.body.appencdChild(new_element)
*/
因此,你有一个对该元素的引用,你可以通过javascript设置属性。
new_element.setAttribute('id', 'new-element-id')
//<div id='new-element-id' ...
new_element.classList.add('lorem')
//<div id='new-element-id' class='lorem' ...
new_element.classList.add('ipsum')
//<div id='new-element-id' class='lorem ipsum' ...
如果要添加多个元素,这也不难。
var giants = ['marx', 'engels', 'lenin']
for(i=0; i<giants.length; i++) {
var g = document.createElement('div');
g.setAttribute('id', giants[i]);
document.body.appendChild(g);
}
或者,更时尚
giants.forEach(function(e) {
var g = document.createElement('div');
g.setAttribute('id', e);
document.body.appendChild(g);
})
下面的片段将添加5个div(包括图像和跨度和跨度文本)和一些数据。
insert_divs = function() {
var parent = document.getElementsByClassName("panel-body")[0];
var installments = ['Installment 1', 'Installment 2', 'Installment 3', 'Installment 4', 'Installment 5'];
installments.forEach(function(e){
var sp = document.createElement('span');
var img = document.createElement('img');
var installment = document.createElement('div');
var span_text = document.createTextNode(e);
sp.appendChild(span_text);
img.setAttribute('src', 'https://cdn3.iconfinder.com/data/icons/google-material-design-icons/48/ic_cancel_48px-128.png')
installment.classList.add('panel-more1');
installment.appendChild(img);
installment.appendChild(sp);
parent.appendChild(installment);
});
}
window.onload = insert_divs
<div id="listContainer">
<div>
<ul class="list-group">
<li>
<div class="panel-body panel panel-default" style="height: 70px;">
<div class="panel-info">
<p><strong>Shailendra Kushwah</strong></p>
</div>
</div>
</li>
</ul>
</div>
</div>