将Javascript for循环的结果写入HTML5表中
Writing the result of a Javascript for-loop into a HTML 5 table
我正在玩Javascript,我制作了一个虚构的酒店网站,当你点击按钮时,它会向你显示酒店的详细信息。
http://jsfiddle.net/addiosamigo/4ev43b5m/8/
var hotel = {Name: "Park Hotel", Price: "£120.00", Rooms: 50}
var hotel2 = {name: "West End", price: "£240.00", rooms: 150}
el_p = document.getElementById("para1");
el_picture = document.getElementById("picture");
el_picture2 = document.getElementById("picture2");
function showPrice() {
el_picture2.style.display = "none";
el_picture.style.display = "block";
el_p.innerHTML = " ";
for(details in hotel) {
el_p.innerHTML += (details += ": " + hotel[details] + "<br />");
}
}
function showPrice2() {
el_picture.style.display = "none";
el_picture2.style.display = "block";
el_p.innerHTML = " ";
for(details in hotel2) {
el_p.innerHTML += ( details += ": " + hotel2[details] + "<br />");
}
}
首先,有没有一种更简单的编码方法?我只是在学习,所以我只是尽我所能。
其次,我如何将for循环的结果写入表中?
感谢
这里是一个使用HTML模板和纯javascript而不是jQuery的javascript版本。
http://jsfiddle.net/dr6n88bu/15/
<script type="text/template" id="hotelTemplate">
<img src="{img}" />
<table>
<tr>
<td>Name: </td>
<td>{name}</td>
</tr>
<tr>
<td>Price: </td>
<td>{price}</td>
</tr>
<tr>
<td>Rooms: </td>
<td>{rooms}</td>
</tr>
</table>
</script>
我建议您使用jQuery库(基于JS)。
1) 创建酒店阵列:
var hotels = [
{name: "Park Hotel", price: "£120.00", rooms: 50},
{name: "West End", price: "£240.00", rooms: 150}
];
2) 创建空表:
<table id="hotelsTalbe">
<thead>
<tr>
<th>Hotel name</th>
<th>Price per room</th>
<th>No. of rooms</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
3) 而不仅仅是循环你的hotels
:
// Load jQuery first!
$.each(hotels, function(key, row){
// this - current element in loop. $(this) - current jQuery element.
$('#hotelsTable tbody').append(
'<tr><td>'
+ row['name'] + '</td><td>'
+ row['price'] + '</td><td>'
+ row['rooms'] + '</td></tr>'
);
});
在JS中(未测试):
for (var i = 0; i < hotels.lenth; i++) {
var tr = document.createElement("tr");
var td = document.createElement("td");
var text = document.createTextNode(hotels[i]['name']);
td.appendChild(textnode);
tr.appendChild(td);
document.querySelector("#hotelsTable tbody").appendChild(tr);
td = document.createElement("td");
text = document.createTextNode(hotels[i]['price']);
td.appendChild(textnode);
tr.appendChild(td);
td = document.createElement("td");
text = document.createTextNode(hotels[i]['rooms']);
td.appendChild(textnode);
tr.appendChild(td);
document.querySelector("#hotelsTable tbody").appendChild(tr);
}
相关文章:
- 用程序搜索JQuery数据表中的文本
- 使用谷歌应用程序脚本从工作表中获取值并将其显示在文本框中
- 可以'我不明白为什么;t将行和单元格添加到表中
- 将行添加到具有固定标题的HTML表中
- 表中单元格的总和
- 将数组中的值插入到表中
- 如何首先设置样式<td>表中包含在窗体中的元素
- 通过单击动态加载的表中同一行的另一个字段来更新一行的字段
- html5视频中的Youtube类型注释
- 如何使用Javascript和HTML5数据库替换表中的现有联系人
- html5:将tr拖动到另一个表中
- 有没有一种新的HTML5方法可以使用箭头键在表中的输入行之间移动
- 将Javascript for循环的结果写入HTML5表中
- 在IE中使用新的html5表单属性序列化失败
- 使用AngularJs的ng-model在html5表单中格式化电话号码和TaxId号码
- 如何在postgres表中为使用html5地图的用户保存用户的经度和纬度?
- 我如何在html5表单中添加确认对话框到提交按钮
- HTML5通知中的表单元素
- 在HTML5画布中创建表
- HTML5表单占位符未出现在IE中