简体   繁体   English

从数组元素创建 div

[英]Create divs from Array elements

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?是否可以为我的 HTML 页面中的每个数组元素创建像<div id="results"></div>这样的 div?

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:如果您愿意,您也可以在原版 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;值得考虑id的来源; if more than one element 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 must be unique within the document.如果此for循环要生成多个元素,最好使用class代替(取决于分配id的位置和方式),就像我在我的两个建议中所做的那样,因为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.虽然这个答案是很久以前写的,但我觉得值得更新以反映(相对较新的) Array.prototype.forEach()提供的可能性,它遍历给定数组的每个元素,并为每个元素应用 function迭代。 For example, given the HTML:例如,给定 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:导致 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:参考:

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/

A Basic For Loop + jQuery should do it.一个基本的 For 循环 + jQuery 应该可以做到。 Just replace body with a selector for the container you want to add the divs to.只需将body替换为要添加 div 的容器的选择器即可。 Here is a fiddle showing the technique in use.这是一个显示正在使用的技术的小提琴

var myCars=new Array("Saab","Volvo","BMW");

for(var x=0; x<myCars.length; x++){
    $('body').append('<div id="' + myCars[x] + '">' + myCars[x] + '</div>');
}

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()文档,并将 id 更改为 class 因为 id 需要是唯一的。

demo at http://jsfiddle.net/gaby/FuPF7/演示在http://jsfiddle.net/gaby/FuPF7/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM