我正在玩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循环的结果写入表格?
感谢
答案 0 :(得分:1)
这是一个使用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>
答案 1 :(得分:0)
我建议你使用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);
}