首次使用JSON API。请告诉我在哪里以及我做错了什么。这是来自freeCodeCamp的挑战。我们需要建立一个随机报价机。
一旦我点击New Quote按钮就应该给我们一个随机引用。在jQuery中我循环浏览json和click函数必须用JSON中的新随机引用来改变当前的h2 class = text。
项目在这里http://codepen.io/ekilja01/full/Lbdbpd/。
请帮忙。
这是我的 HTML :
<div class="container-fluid">
<div class = "well">
<div class="row">
<h2 class="text text-center"><i class="fa fa-quote-left"> </i> Hey, what when and why there is no and yes?</h2>
<p class="author">-Alina Khachatrian</p>
<div class="buttons">
<div class="row">
<div class="col-xs-6">
<a id="tweet-quote" title="Tweet current quote" target="_blank" href="#">
<i class="fa fa-twitter fa-2x"></i>
</a>
</div>
<div class="col-xs-6">
<button type="button" class="btn btn-default btn-transparent" id ="getNewQuote" title="Get a new quote">New Quote</button>
</div>
</div>
<footer class="text-center">
<hr>
<p>Written and coded by <a href="https://github.com/edkiljak">Edgar Kiljak</a>.</p>
</footer>
</div>
</div>
和 JS :
$(document).ready(function(){
$(".btn").on("click", function(){
$.getJSON("http://quotes.rest/qod.json", function (json) {
var html = "";
json.forEach(function(val){
var keys = Object.keys(val);
html += "<div class = 'newQuote>'";
"<h2 = '" + val.quote + "'>";
html += "</h2>";
html += "</div>";
})
$(".text").html(html);
});
});
});
和 JSON :
{
"success": {
"total": 1
},
"contents": {
"quotes": [
{
"quote": "Great things are done by a series of small things brought together.",
"length": "67",
"author": "Vincent Van Gogh",
"tags": [
"inspire",
"small-things",
"tso-art"
],
"category": "inspire",
"date": "2016-12-10",
"title": "Inspiring Quote of the day",
"background": "https://theysaidso.com/img/bgs/man_on_the_mountain.jpg",
"id": "DLThmumKP4CCe1833rRvNQeF"
}
]
}
}
答案 0 :(得分:0)
请发布您遇到的错误。
同样在你的.js文件中,你正在做:
"<h2 = '" + val.quote + "'>";
应该是
"<h2>'" + val.quote + "'</h2>";
另一个建议是将代码放在你处理响应的地方.done()。据我所知,这种方法可以使用$ .get()方法。
来自jQuery Docs,
$.get( "test.cgi", { name: "John", time: "2pm" } )
.done(function( data ) {
alert( "Data Loaded: " + data );
});
答案 1 :(得分:0)
你的问题在这里:json.forEach(function(val)
...
因为JSON不是数组,所以它应该是:json.contents.quotes.forEach(function(val)
json.contents.quotes
是一个数组([括号]而不是{}),forEach仅用于数组