var quotes = [
{
'value': 'Ask Not What Your Country Can Do For You...',
'tags': ['inspirational', 'patriotic']
},
{
'value': 'It Ain\'t Over Till It\'s Over',
'tags': ['inspirational', 'funny']
},
{
'value': '60% Of The Time, It Works Every Time',
'tags': ['funny']
},
{
'value': 'Funny and serious quote',
'tags': ['funny', 'serious']
},
{
'value': 'Inspirational and serious quote',
'tags': ['inspirational', 'serious']
},
{
'value': 'All tags quote 1',
'tags': ['inspirational', 'serious', 'funny', 'patriotic']
},
{
'value': 'All tags quote 2',
'tags': ['inspirational', 'serious', 'funny', 'patriotic']
},
{
'value': 'All tags quote 3',
'tags': ['inspirational', 'serious', 'funny', 'patriotic']
},
{
'value': 'All tags quote 4',
'tags': ['inspirational', 'serious', 'funny', 'patriotic']
}
// Etc...
];
var getQuoteButton = document.getElementById('get-quote');
function getQuote() {
var currentTag, randomIndex, randomQuote;
var matchingQuotes = [];
var category = document.getElementById('quote-category').value;
if (category !== 'all') {
// Iterate through list of all quotes
for (var quoteIndex = 0, quotesLen = quotes.length; quoteIndex < quotesLen; quoteIndex++) {
// Iterate through current quote's tags
for (var tagIndex = 0; tagIndex < quotes[quoteIndex].tags.length; tagIndex++) {
currentTag = quotes[quoteIndex].tags[tagIndex];
if (currentTag === category) {
// Add matching quotes to array
matchingQuotes.push(quotes[quoteIndex].value);
}
}
}
randomIndex = Math.floor(Math.random() * matchingQuotes.length);
randomQuote = matchingQuotes[randomIndex];
}
else {
// If 'All' is selected, choose randomly from all quotes
randomIndex = Math.floor(Math.random() * quotes.length);
randomQuote = quotes[randomIndex].value;
}
document.getElementById('quote').innerHTML = randomQuote;
}
getQuoteButton.onclick = getQuote;
<label>Select A Category
<select name='quote-category' id='quote-category'>
<option value='all'>All</option>
<option value='funny'>Funny</option>
<option value='inspirational'>Inspirational</option>
<option value='serious'>Serious</option>
<option value='patriotic'>Patriotic</option>
</select>
<button id='get-quote'>Get Quote</button>
<div id='quote'></div>
Tamam mükemmel! Bir soru, sonucu nasıl geciktirebilirim? Eğer kategori seçilirse, bir yükleme işareti veya bir şekilde bir gecikme olmalı, bunu nasıl yapabilirim? ;) Teşekkürler! – sooony
evet [setTimeout] ile yapabilirsiniz (https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout). – Gintoki
Gerçekten javascript için yeni, bu yüzden zaman aşımı işlevini nereye yerleştireceğiniz veya nasıl bağlanacağınız hakkında hiçbir fikrim yok ..:/ – sooony