我想隨機引用這是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使其正確。謝謝! –