<script>
$(document).ready(function() {
$("#getMessage").on("click", function() {
$.getJSON("/json/cats.json", function(json) {
var html = "";
// Only change code below this line.
json.forEach(function(val){
var keys = Object.keys(val);
html+="<div class='cat'>";
keys.forEach(function(key){
html+="<strong>"+key+"</strong>;"+val[key]+"<br>";
});
html+="</div><br>";
});
// Only change code above this line.
$(".message").html(html);
});
});
});
</script>
<div class="container-fluid">
<div class = "row text-center">
<h2>Cat Photo Finder</h2>
</div>
<div class = "row text-center">
<div class = "col-xs-12 well message">
The message will go here
</div>
</div>
<div class = "row text-center">
<div class = "col-xs-12">
<button id = "getMessage" class = "btn btn-primary">
Get Message
</button>
</div>
</div>
</div>
所以我是一名业余前端开发人员,我刚刚完成了一些基本的JS并开始学习json和jquery,但是上面这段代码已经过了我的脑海。 有人可以解释它的javascript部分。
答案 0 :(得分:0)
$(document).ready(function() { // means that whenever the document is ready you get an annonimous function
$("#getMessage").on("click", function() {// this is jQuery selector for an element in the DOM called getMEssage (this is the ID)
$.getJSON("/json/cats.json", function(json) { // this gets the JSON data from /json/cats.json
var html = ""; //you create an empthy variable called html
// Only change code below this line.
json.forEach(function(val){ // you go over each element in the json object that came from the cats.json file
var keys = Object.keys(val); // you get the key
html+="<div class='cat'>";// you add a div element with the class cat to the html variable you did create at every iteration
keys.forEach(function(key){ //you itewrate over all keys
html+="<strong>"+key+"</strong>;"+val[key]+"<br>"; // you add the key (in bold text) + the value for the key (not in bold) to the html and you break the row
});
html+="</div><br>"; // now you close the div element and you break the row
});
// Only change code above this line.
$(".message").html(html); // then you select all the elements with the message class and you set their html to be equal to your variable called html
});
});
});
希望它有所帮助。 祝一切顺利, PIY
答案 1 :(得分:0)
{{1}}
答案 2 :(得分:0)
对于任何给定的json input
数组,您可以映射它并返回每个元素的字符串表示形式。
let input = [
{ name: 'Foo', id: 42 },
{ name: 'Bar', id: 1337 },
{ name: 'Biz', id: 12 }
];
let elems = input.map(e => `<li>${e.name} (${e.id})</li>`);
document.querySelector('#list').innerHTML = elems.join('');
<ul id="list"></ul>