我是 Javascript 新手,我在每 3 個 div 之后關閉 div 到一個回圈以重新啟動 div 列時遇到問題。盡管它清楚地添加了新的 div ,但 Javascript 拒絕添加關閉 div(參見下面的代碼)。預先感謝您的幫助。
var cats = 8;
var cat= '';
for(var i=1; i<=cats; i ) {
cat = "<div class=\"cat three_columns two_columns\">" i "</div>";
if(i%3==0) {cat = "</div><div class=\"column\">";}
}
var threecolumns = document.getElementsByClassName('column');
threecolumns[0].innerHTML = cat;
<style type="text/css">
* { box-sizing: border-box;}
.columnsBox {width:90%; padding:10px; margin:0 auto; border:1px solid green; overflow:auto;}
.column {float:left; width:100%; padding-right:8px;}
.cat {font-size:16px; text-align:center; margin-bottom:10px;padding:12px; color:#5a2e0f; background-color:#d7d7d7; border:1px solid #c1bfbf; outline:none; cursor:pointer;}
</style>
<div style="width:90%; min-width:200px; margin:0 auto; padding:10px; ">
<div class="columnsBox">
<div class="column"></div>
This is where I placed the javascript
</div>
</div>
Desired Output:
<div class="columnsBox">
<div class="column">
<div class="cat three_columns two_columns">1</div>
<div class="cat three_columns two_columns">2</div>
<div class="cat three_columns two_columns">3</div>
</div>
<div class="column">
<div class="cat three_columns two_columns">4</div>
<div class="cat three_columns two_columns">5</div>
<div class="cat three_columns two_columns">6</div>
</div>
<div class="column">
<div class="cat three_columns two_columns">7</div>
<div class="cat three_columns two_columns">8</div>
</div>
</div>
uj5u.com熱心網友回復:
您傳遞給的字串innerHTML必須是一段自包含的 HTML。它無法關閉未在其中打開的標簽。這種關閉</div>被忽略。
為了克服這個問題,我建議使用以下方法創建元素createElement:
let cats = 8;
let div;
let container = document.querySelector(".columnsBox");
for (let i = 1; i <= cats; i ) {
if (i % 3 == 1) {
column = document.createElement("div");
column.className = "column";
container.appendChild(column);
}
let child = document.createElement("div");
child.className = "cat three_columns two_columns";
child.textContent = i;
column.appendChild(child);
}
* {
box-sizing: border-box;
}
.columnsBox {
width:90%;
padding:10px;
margin:0 auto;
border:1px solid green;
overflow:auto;
}
.column {
float:left;
width:100%;
padding-right:8px;
}
.cat {
font-size:16px;
text-align:center;
margin-bottom:10px;
padding:12px;
color:#5a2e0f;
background-color:#d7d7d7;
border:1px solid #c1bfbf;
outline:none;
cursor:pointer;
}
.three_columns {
width: 30%;
display: inline-block;
margin: 5px;
}
<div style="width:90%; min-width:200px; margin:0 auto; padding:10px; ">
<div class="columnsBox">
</div>
</div>
uj5u.com熱心網友回復:
這是另一種方式。使用 2 個回圈。我將輸出顯示為<pre>html,以便您可以看到結構。
let cats = 8,
numCols = 3,
x = 0,
catsPerCol = Math.max(cats / numCols),
output = "";
for (let r = 0; r < numCols; r ) {
output = `<div >\n`;
for (let c = 0; c < catsPerCol; c ) {
if (x < cats) output = ` <div >${x}</div>\n`;
}
output = `</div>\n`;
}
document.querySelector('.columnsBox').innerText = output;
<pre class="columnsBox"></pre>
uj5u.com熱心網友回復:
使用生成器函式的解決方案
您還可以使用生成器函式來創建相同的結果。這需要一些更高級的 JavaScript,并且不是最有效的解決方案(與大多數用例無關),但可以是一個非常優雅的解決方案,無需使用取模運算子。
// wait for HTML to load
window.addEventListener("DOMContentLoaded", (e) => {
// get parent component which holds all columns
const colBox = document.querySelector(".columnsBox");
// number of total categories
const cats = 8;
// number of categories per column
const catsPerColumn = 3;
// create all categories
const allDivs = [...new Array(cats)].map((_, idx) => createCategory(idx 1));
// create a column for every catsPerColumn elements
for (const columnChildren of chunksArray(allDivs, catsPerColumn)) {
const newCol = createColumn(columnChildren);
colBox.appendChild(newCol);
}
});
/**
* Creates a category div
* @param {number} id ID for the column
* @returns div within a column
*/
function createCategory(id) {
const newCol = document.createElement("div");
// add classes to this div
newCol.classList.add("cat", "three_columns", "two_columns");
newCol.textContent = id;
return newCol;
}
/**
* Create a column containing children
* @param {Iterable<HTMLElement>} columnChildren
* @returns column with children
*/
function createColumn(columnChildren) {
const newColumn = document.createElement("div");
// add class to this div
newColumn.classList.add("column");
// all all divs that belong to that column to it
newColumn.append(...columnChildren);
// add column to column box
return newColumn;
}
/**
* Generator function which returns all elements of an array in chunks of a specified size (or smaller if there are not enough values in array)
* @param {Array<any>} array an array
* @param {number} chunkSize size of one chunk
*/
function* chunksArray(array, chunkSize) {
let cur = 0;
do {
// create a new array only holding the values from the current value till current value chunkSize or till the end of the array
yield array.slice(cur, Math.min(cur chunkSize, array.length));
cur = chunkSize;
} while (cur <= array.length);
}
* {
box-sizing: border-box;
}
.columnsBox {
width: 90%;
padding: 10px;
margin: 0 auto;
border: 1px solid green;
overflow: auto;
}
.column {
float: left;
width: 100%;
padding-right: 8px;
border: 5px solid black;
}
.cat {
font-size: 16px;
text-align: center;
margin-bottom: 10px;
padding: 12px;
color: #5a2e0f;
background-color: #d7d7d7;
border: 1px solid #c1bfbf;
outline: none;
cursor: pointer;
}
<div class="columnsBox">
請注意:我添加了一個黑色粗邊框來顯示哪些
<div>s 屬于同一列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/463966.html
標籤:javascript 循环 模数
上一篇:如何在外部try/catch塊上捕獲異步回呼函式的錯誤
下一篇:未呈現新的屬性值
