将js数组中的数据显示到html的下拉框、table、<ul>+<li>等标签上
时间: 2024-03-18 07:40:29 浏览: 98
好的,我可以为您提供一些参考代码:
1. 将数组数据显示在下拉框中:
```html
<select id="mySelect"></select>
```
```javascript
const myArray = ["apple", "banana", "orange"];
const mySelect = document.getElementById("mySelect");
for(let i = 0; i < myArray.length; i++) {
let option = document.createElement("option");
option.text = myArray[i];
mySelect.add(option);
}
```
2. 将数组数据显示在table中:
```html
<table id="myTable">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
```
```javascript
const myArray = [
{ col1: "Value 1", col2: "Value 2", col3: "Value 3" },
{ col1: "Value 4", col2: "Value 5", col3: "Value 6" },
{ col1: "Value 7", col2: "Value 8", col3: "Value 9" }
];
const myTableBody = document.getElementById("myTable").getElementsByTagName("tbody")[0];
for(let i = 0; i < myArray.length; i++) {
let row = myTableBody.insertRow(i);
let cell1 = row.insertCell(0);
let cell2 = row.insertCell(1);
let cell3 = row.insertCell(2);
cell1.innerHTML = myArray[i].col1;
cell2.innerHTML = myArray[i].col2;
cell3.innerHTML = myArray[i].col3;
}
```
3. 将数组数据显示在ul+li标签中:
```html
<ul id="myList"></ul>
```
```javascript
const myArray = ["apple", "banana", "orange"];
const myList = document.getElementById("myList");
for(let i = 0; i < myArray.length; i++) {
let li = document.createElement("li");
li.innerHTML = myArray[i];
myList.appendChild(li);
}
```
希望这些代码可以帮助您实现您的需求。
阅读全文