[英]Hot to create a list dynamically with html and css
我正在做作業,並且用html,css,javascript編寫了前端。 直到現在,當我按下按鈕時,我都會從后端獲取一些數據,並在javascript中解析響應。 響應是一組項目。 一個項目是一個結構。 我想要的是動態構建這些項目的列表。 我在Google上找不到用javascript做到這一點的方法。 一些提示/幫助?
您在下面看到的我嘗試過的操作是將一些HTML附加到HTML元素上-沒用。
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
source.value = "";
destination.value = "";
var array_rides = JSON.parse(this.responseText).results;
var rides_length = array_rides.length;
for (var i = 0;i < rides_length;i++) {
console.log(array_rides[i][DRIVER]);
console.log(array_rides[i][RIDERS]);
console.log(array_rides[i][SOURCE]);
console.log(array_rides[i][DESTINATION]);
console.log(array_rides[i][START]);
console.log(array_rides[i][SEATS_AVAILABLE]);
console.log(array_rides[i][SEATS_TOTAL]);
my_list.append('<span class="name">{0}</span>'.format(array_rides[i][DRIVER]));
}
}
};
因此,我想要一個動態填充的列表。 像(餐桌):
array_rides[0][DRIVER], array_rides[0][RIDERS], ...
array_rides[1][DRIVER], array_rides[1][RIDERS], ...
...
array_rides[n][DRIVER], array_rides[n][RIDERS], ...
當然,要繼承一些CSS。
我假設文檔中有一個列表,例如產品表或其他內容。
最簡單的方法是循環瀏覽列表並將其插入表或其他內容。 一個例子可能是這樣的:
function somefunc() { var table = document.getElementById('my_table'); var array_rides = ['cell1', 'cell2', 'cell3', 'cell4']; var string; string = "<table>"; for (var i = 0;i < array_rides.length;i++) { //add table row string += "<tr>"; //add all items in tabel cells //you just have to replace the array_rides[i] with array_rides[i].DRIVER, array_rides[i].RIDERS... and so on string += "<td>"+array_rides[i]+"</td>"; string += "<td>"+array_rides[i]+"</td>"; string += "<td>"+array_rides[i]+"</td>"; string += "<td>"+array_rides[i]+"</td>"; string += "<td>"+array_rides[i]+"</td>"; string += "<td>"+array_rides[i]+"</td>"; //close table row string += "</tr>"; } string += "</table>"; table.innerHTML = string; }
table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Testpage</title> </head> <body onload="somefunc();"> <div id="my_table"></div> </body> </html>
基本上,這是從數組中獲取所有數據並將它們附加到表中的。 您也可以添加一些CSS,使其看起來更好
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.