I am trying a JavaScript challenge but get stuck badly. The requirement is not to modify any other files except app.js
and no library (i.e. no JQuery etc.)
Here is the file system:
css
bootstrap.min.css
image
1.gif
2.gif
3.gif
4.gif
5.gif
js
app.js
json
data.js
sample.html
Here is the sample.html:
<!doctype>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
<title>Sample</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h2>Only Pure JavaScript</h2>
<div class="contents">
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Image</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script src="json/data.js"></script>
<script src="js/app.js"></script>
</body>
</html>
Here is the data.js:
var sample_data = [
{
"id": "5",
"name": "name #5",
"thumbnailUrl": "image/5.gif",
"price": 170
},
{
"id": "1",
"name": "name #1",
"thumbnailUrl": "image/1.gif",
"price": 170
},
{
"id": "2",
"name": "name #2",
"thumbnailUrl": "image/2.gif",
"price": 270
},
{
"id": "8",
"name": "name #8",
"thumbnailUrl": "image/8.gif",
"price": 70
},
{
"id": "10",
"name": "name #10",
"thumbnailUrl": "image/10.gif",
"price": 170
},
]
And this is what I have in app.js currently:
var jsonFile = "json/data.js";
var len = sample_data.length;
// document.write('len: ' + len + "<br>");
var table = document.createElement('table');
var body = document.createElement('tbody');
for (var i = 0; i < len; i++) {
var tr = document.createElement('tr');
var td = document.createElement('td');
var s = sample_data[i];
document.write('id: ' + s.id + "<br>");
td.innerHTML = s.id;
tr.appendChild(td);
td = document.createElement('td');
document.write('name: ' + s.name + "<br>");
td.innerHTML = s.name;
tr.appendChild(td);
td = document.createElement('td');
document.write('thumbnailUrl: ' + s.thumbnailUrl + "<br>");
td.innerHTML = s.thumbnailUrl;
tr.appendChild(td);
td = document.createElement('td');
document.write('price: ' + s.price + "<br>");
td.innerHTML = s.price;
tr.appendChild(td);
body.appendChild(tr);
}
table.appendChild(body);
I've spent so much time and tried 4 different ways and this one attached is the closest I can get (it shows correctly with document.write
). Seriously, without any library or changes in the html page, it is hard for me. Any help or direction of where to look for information will be greatly appreciated. Remember, only app.js
can be changed for this.