我的按钮用于在页面加载和单击按钮时显示随机引用。在我的JS文件(第17行)中看起来“引用”未定义,但我不确定如何解决这个问题。知道我做错了什么吗?我非常感谢你的帮助。
HTML:
<button id="submit" type="button">Get new quote!</button>
<span id="quoteText"></span>
<span id="authorText"></span>
JSON:
{ "quotes" : [
{
"text": "Whatever you are, be a good one.", "author": "Abraham Lincoln", "provider": "Bennett",
"tags":["Famous Inspirational Quotes", "BrainyQuote.com", "President Lincoln"]
},
{
"text": "It has been my philosophy of life that difficulties vanish when faced boldly.", "author": "Isaac Asimov", "provider": "Bennett",
"tags":["Famous Inspirational Quotes", "BrainyQuote.com", "Science Fiction"]
},
{
"text": "Enjoy life. There’s plenty of time to be dead.", "author": "Anonymous", "provider": "Bennett",
"tags":["Famous Inspirational Quotes", "BrainyQuote.com", "Anonymous Quote"]
},
{
"text": "Every moment is a fresh beginning.", "author": "T.S. Eliot", "provider": "Bennett",
"tags":["Famous Inspirational Quotes", "BrainyQuote.com", "Author T.S. Eliot"]
},
{
"text": "One day your life will flash before your eyes. Make sure it is worth watching.", "author": "Anonymous", "provider": "Bennett",
"tags":["Famous Inspirational Quotes", "BrainyQuote.com", "President Lincoln"]
}
]}
JS:
$(function()
{
var quoteSpan = $("#quoteText");
var authorSpan = $("#authorText");
var submitButton = $('#submit');
var data;
$.getJSON("quotes.json", function(data) {
window.alert(data);
});
var oldQuoteIndex = -1;
var newQuoteIndex;
function nextQuote() {
do {
newQuoteIndex = Math.floor(Math.random() * data.quotes.length);
} while (newQuoteIndex == oldQuoteIndex);
quoteSpan.text(data.quotes[newQuoteIndex].text);
authorSpan.text(data.quotes[newQuoteIndex].author);
oldQuoteIndex = newQuoteIndex;
}
submitButton.click(nextQuote);
nextQuote();
});
答案 0 :(得分:0)
从nextQuote
回调中调用getJSON
函数,并从那里设置事件。然后,您就可以访问收到的数据。
$(function()
{
var quoteSpan = $("#quoteText");
var authorSpan = $("#authorText");
var submitButton = $('#submit');
var mydata;
var oldQuoteIndex = -1;
var newQuoteIndex;
$.getJSON("quotes.json", function(data) {
mydata = data;
nextQuote();
submitButton.click(nextQuote);
});
function nextQuote() {
do {
newQuoteIndex = Math.floor(Math.random() * mydata.quotes.length);
} while (newQuoteIndex == oldQuoteIndex);
quoteSpan.text(mydata.quotes[newQuoteIndex].text);
authorSpan.text(mydata.quotes[newQuoteIndex].author);
oldQuoteIndex = newQuoteIndex;
}
});