js遍历json数组给html td赋值,JS实现给json数组动态赋值的方法示例_咋地 _前端开发者...
时间: 2023-12-20 13:07:26 浏览: 104
可以使用 JavaScript 的 forEach 方法遍历 JSON 数组,然后使用 DOM 操作给 HTML 的 td 元素赋值。示例代码如下:
HTML 代码:
```
<table>
<tr>
<td id="name"></td>
<td id="age"></td>
</tr>
</table>
```
JavaScript 代码:
```javascript
var data = [
{
"name": "张三",
"age": 20
},
{
"name": "李四",
"age": 25
}
];
data.forEach(function(item) {
document.getElementById("name").innerHTML += item.name + "<br/>";
document.getElementById("age").innerHTML += item.age + "<br/>";
});
```
该代码会将 JSON 数组 data 中的每个对象的 name 和 age 属性的值分别赋值给 HTML 的两个 td 元素。需要注意的是,这里使用了 innerHTML 属性来给 td 元素赋值,并且使用了 += 运算符来将每个对象的值拼接在一起。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)