Javascript 从数组元素创建 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5886144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create divs from Array elements
提问by mike643
I have different strings in my array. Is it possible to create a divs like
<div id="results"></div>
for each array element in my HTML page?
我的数组中有不同的字符串。是否可以为<div id="results"></div>
我的 HTML 页面中的每个数组元素创建一个 div
?
采纳答案by Shaz
Sure, simple example without using any frameworks or libraries:
当然,不使用任何框架或库的简单示例:
var cars = 'Saab,Volvo,BMW,GMC,Nissan,Ford'.split(',');
for (var c in cars) {
var newElement = document.createElement('div');
newElement.id = cars[c]; newElement.className = "car";
newElement.innerHTML = cars[c];
document.body.appendChild(newElement);
}
You can take a look at how this works using jsFiddle here: http://jsfiddle.net/Shaz/geNNa/
您可以在此处使用 jsFiddle 看看这是如何工作的:http: //jsfiddle.net/Shaz/geNNa/
回答by David says reinstate Monica
Yeah, using a for
loop:
是的,使用for
循环:
var arrayVariable = ['one','two','three'],
arrayLength = arrayVariable.length;
for (i = 0; i < arrayLength; i++) {
$('<div class="results" />').text(arrayVariable[i]).appendTo('body');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Or slightly more jQuery-fied:
或者稍微更 jQuery-fied:
var arrayVariable = ['one', 'two', 'three'];
$.each(arrayVariable, function(index, value) {
$('<div />', {
'text': value
}).appendTo('body');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You could do this in vanilla JavaScript too, if you'd prefer:
如果您愿意,您也可以在 vanilla JavaScript 中执行此操作:
var arrayVariable = ["one", "two", "three"];
var arrayLength = arrayVariable.length;
var temp;
for (i = 0; i < arrayLength; i++) {
temp = document.createElement('div');
temp.className = 'results';
temp.innerHTML = arrayVariable[i];
document.getElementsByTagName('body')[0].appendChild(temp);
}
It's worth considering where the id
is coming from; if more than oneelement is to be produced by this for
loop, it might be better (depending on where, and how, the id
is assigned) to use a class
instead, as I did in both of my suggestions, as the id
mustbe unique within the document.
值得考虑的id
是从哪里来;如果超过一个元素是由该生产for
循环中,它可能会更好(这取决于在哪里,以及如何将id
被分配)使用class
,而不是,因为我在我的两个建议做了,因为id
必须是内唯一文档。
While this answer was written quite a while ago, I felt it worth updating to reflect the possibilities offered by the (relatively new) Array.prototype.forEach()
, which iterates over each element of a given array, and applies a function for each iteration. For example, given the HTML:
虽然这个答案是很久以前写的,但我觉得值得更新以反映 (相对较新) 提供的可能性Array.prototype.forEach()
,它迭代给定数组的每个元素,并为每次迭代应用一个函数。例如,给定 HTML:
<ul id="fruits"></ul>
And the JavaScript:
和 JavaScript:
var fruitsList = document.getElementById('fruits'),
li = document.createElement('li'),
clone;
['apples','bananas','cranberries'].forEach(function (fruit, index) {
clone = li.cloneNode();
clone.textContent = index + ': ' + fruit;
fruitsList.appendChild(clone);
});
Resulting in the output:
导致输出:
<ul id="fruits">
<li>0: apples</li>
<li>1: bananas</li>
<li>2: cranberries</li>
</ul>
var fruitsList = document.getElementById('fruits'),
li = document.createElement('li'),
clone;
['apples', 'bananas', 'cranberries'].forEach(function(fruit, index) {
clone = li.cloneNode();
clone.textContent = index + ': ' + fruit;
fruitsList.appendChild(clone);
});
<ul id="fruits"></ul>
References:
参考:
- JavaScript:
- jQuery:
回答by Dutchie432
A Basic For Loop + jQuery should do it. Just replace body
with a selector for the container you want to add the divs to. Here is a fiddleshowing the technique in use.
一个基本的 For 循环 + jQuery 应该可以做到。只需将body
要添加 div 的容器替换为选择器即可。这是一个显示正在使用的技术的小提琴。
var myCars=new Array("Saab","Volvo","BMW");
for(var x=0; x<myCars.length; x++){
$('body').append('<div id="' + myCars[x] + '">' + myCars[x] + '</div>');
}
回答by Gabriele Petrioli
You can use
您可以使用
var results = ['result 1', 'result 2', 'result 3'];
$.each(results, function(idx, value){
var newdiv = $('<div>',{class: 'results', text: value});
$('body').append( newdiv );
});
used $.each()
docs, and also changed the id to class since id needs to be unique.
使用$.each()
docs,并且还将 id 更改为 class 因为 id 需要是唯一的。