我想随机引用这是data.JSON文件并将其追加到一些DIV的,但我得到的错误无论身在何处,我把我的变量:从JSON获取随机引号并将其附加到div。
我的JS文件:
$(specBut).click(function() {
var randomQuote;
$.getJSON('data.json',function(quotes){
randomQuote = quotes[Math.floor(Math.random() * quotes.length)];
});
$('.quote').empty().append(randomQuote.quote);
$('.quote-author').empty().append(randomQuote.author);
});
而且我data.JSON文件:
{
"quotes":
[{
"author": "First author",
"quote": "First"
}, {
"author": "Second author",
"quote": "Second"
}, {
"author": "Third author",
"quote": "Third"
}, {
"author": "Last author",
"quote": "last one"
}]
}
我得到这个错误:
Uncaught TypeError: Cannot read property 'quote' of undefined
这是我的HTML看起来像:
<div class="quote-box">
<div class="head text-center"><h2>Random Quotes!</h2></div>
<div class="quote"> </div>
<div class="quote-author"></div>
<div class="buttons">
<a class="btn btn-default" id="specBut" href="#" role="button">New RQ</a>
</div>
</div>
我认为你应该使用'quotes.quotes' – Mohammad
'quotes'在回调中的值是什么? – eavidan
这是正确的,它适用于我,因为当我打印console.log(引号);我得到“对象{引用:数组[4]}”,所以我的数组被包装在对象中,我需要quotes.quotes使其正确。谢谢! –