如何将数组项附加到html elemnt,如下所示:
[1,2,3]
<div class="bi bj">
<div class="bi bj">
<strong>Suggestions</strong>
<div><label class="bo bp"><input type="checkbox" name="addees[0]" value="0">Default</label></div>
</div>
</div>
所以它会是这样的:
<div class="bi bj">
<div class="bi bj">
<strong>Suggestions</strong>
<div><label class="bo bp"><input type="checkbox" name="addees[0]" value="0">Default</label></div>
<div><label class="bo bp"><input type="checkbox" name="addees[1]" value="1">Test 1</label></div>
<div><label class="bo bp"><input type="checkbox" name="addees[2]" value="2">Test 2</label></div>
<div><label class="bo bp"><input type="checkbox" name="addees[3]" value="3">Test 3</label></div>
</div>
</div>
到目前为止,我知道如何按类名选择div
document.getElementsByClassName("bi bj")[2];
答案 0 :(得分:0)
我强烈建议您阅读一些js和jquery教程。
答案(它使用jquery)
<div class="bi bj" id="uniqueId">
<strong>Suggestions</strong>
<div><label class="bo bp"><input type="checkbox" name="addees[0]" value="0">Default</label></div>
</div>
<script>
$(document).ready(function()) {
var array = [1,2,3];
array.forEach(function(elem){
$('#uniqueId').append('<div><label class="bo bp"><input type="checkbox" name="addees[' + elem + ']" value="' + elem + '">Test' + elem + '</label></div>')
}, this);
}
</script>
答案 1 :(得分:0)
有很多很棒的HTML模板解决方案。就个人而言,我喜欢http://handlebarsjs.com/,但有很多可供选择。我建议你看看。
那就是说,你也可以自己这样做:
var items = [1, 2, 3];
var target = document.querySelector(".bi.bj .bi.bj");
var template = "<div><label class=\"bo bp\"><input type=\"checkbox\" name=\"addees[~id~]\" value=\"~id~\">Test ~id~</label></div>";
items.forEach(function(item) {
target.insertAdjacentHTML("beforeend", template.replace(/~id~/g, item));
});
&#13;
<div class="bi bj">
<div class="bi bj">
<strong>Suggestions</strong>
<div><label class="bo bp"><input type="checkbox" name="addees[0]" value="0">Default</label></div>
</div>
</div>
&#13;
答案 2 :(得分:0)
使用for循环:
for (var i = 0; i <= adees.length(); i++) {
x = document.createElement('div').innerHTML = "<label class='bo bp'><input type='checkbox' name='adees[" + adees[i] + "]' value=" + adees[i] + ">Test " + adees[i] + "</label></div>";
document.body.appendChild(x);
};