英文:
How to separate array into 4 columns and pass to each column 10 <li> items from array?
问题
让我们假设有一个包含40个元素的动态数组(数组随时间不变,但在每次渲染时发生变化)。我想要做的是遍历这个数组并返回4个<div>
元素,每个元素包含10个<li>
元素(这些元素来自我的数组),其中数组中的每个对象都不重复。如何使用JavaScript实现这个目标?
我想要使用一个父级flex容器样式化数组中的对象,其中包含4个<div>
元素,这4个<div>
元素的flex属性为25%,并且<li>
元素是这4个<div>
的子元素。就像这个示例中的方式:w3c。但是我的图片不是静态的,所以无法为每个元素定义样式。
英文:
Lets say there is an dynamic array containing 40 elements (array doesn't change over time, but changes on every render). What I want to do is, loop through this array and return 4 <div> elements, each containing 10 li elements (which are objects from my array), where none object from array is repeated. How to achieve that with JavaScript ?
I wanted to style objects from array with one parent flex container, containing 4 div elements with flex: 25%, and li elements being children of that 4 divs. Like in this example: w3c.
But my images are not static so I can't define each element with typing
答案1
得分: 1
使用JavaScript,您可以像这样操作。
var myArray = [];
var i = 0;
for(i=0;i<40;i++){
myArray.push("Element "+i);
}
var obj = document.getElementById("temp_main");
counter = 10;
firstElement = true;
output = '';
for(i=0;i<40;i++){
var temp = '<div class="row">' + myArray[i] + '</div>';
if(counter>=10){
temp = '<div class="column">' + temp;
if( !firstElement ) temp = '</div>' + temp;
counter = 0;
}
output += temp;
firstElement = false;
counter++;
}
output += '</div>'; //closing last column
obj.innerHTML = output;
.row{
display:block;
box-sizing:border-box;
padding:10;
padding-right:5;
width:100%;
}
.column{
display:block;
box-sizing:border-box;
padding:0px;
width:25%;
border:1px red solid;
float:left;
clear:none;
}
#temp_main{
display:block;
width:100%;
}
<div id="temp_main">
</div>
希望这有所帮助!
英文:
Using javascript you can do something like this.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var myArray = [];
var i = 0;
for(i=0;i<40;i++){
myArray.push("Element "+i);
}
var obj = document.getElementById("temp_main");
counter = 10;
firstElement = true;
output = '';
for(i=0;i<40;i++){
var temp = '<div class="row">' + myArray[i] + '</div>';
if(counter>=10){
temp = '<div class="column">' + temp;
if( !firstElement ) temp = '</div>' + temp;
counter = 0;
}
output += temp;
firstElement = false;
counter++;
}
output += '</div>'; //closing last column
obj.innerHTML = output;
<!-- language: lang-css -->
.row{
display:block;
box-sizing:border-box;
padding:10;
padding-right:5;
width:100%;
}
.column{
display:block;
box-sizing:border-box;
padding:0px;
width:25%;
border:1px red solid;
float:left;
clear:none;
}
#temp_main{
display:block;
width:100%;
}
<!-- language: lang-html -->
<div id="temp_main">
</div>
<!-- end snippet -->
I hope this helps!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论