我制作了一個簡單的參考滑塊,每次單擊時都會隨機更改螢屏上的句子,但我不希望它連續兩次顯示相同的參考。如何從Math.random演算法中排除當前報價并使滑塊在每次點擊時顯示任何其他報價?
(我不希望每個參考只顯示一次,我只想防止滑塊連續顯示相同的參考)
HTML:
<div class="container" onclick="changequote()">
<div class="quote">Sentence 1</div>
<div class="quote">Sentence 2</div>
<div class="quote">Sentence 3</div>
</div>
<script>window.onload = changequote()</script>
JS:
function changequote() {
var random = Math.floor(Math.random() * $('.quote').length);
$('.quote').hide().eq(random).fadeTo(500, 1);
}
CSS:
.quote {
display: none;
}
uj5u.com熱心網友回復:
您可以切換一個類來跟蹤current報價。然后從 的引號中隨機選擇:not(.current)。
此外,我將 javascript 移至 javascript 部分,這確實有助于可維護性。沒有什么比在除錯時傾注 .js 檔案只是為了找出問題源自 html 更合適的了。
function changequote() {
let $quotes = $('.quote:not(.current)');
$('.quote').removeClass('current').hide(); //reset all quotes
$quotes //pick from all quotes except the previously selected one
.eq(Math.floor(Math.random() * $quotes.length))
.addClass('current')
.fadeIn();
}
$('.container').on('click', changequote).click(); //click will initialize on page load
.quote{
cursor: pointer;
display: none;}
<div class="container">
<div class="quote">Sentence 1</div>
<div class="quote">Sentence 2</div>
<div class="quote">Sentence 3</div>
<div class="quote">Sentence 4</div>
<div class="quote">Sentence 5</div>
<div class="quote">Sentence 6</div>
<div class="quote">Sentence 7</div>
<div class="quote">Sentence 8</div>
<div class="quote">Sentence 9</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
uj5u.com熱心網友回復:
只需使用閉包將索引保存到全域變數中
const changeQuote = (() => {
let lastSelectedIndex;
return function() {
let random = Math.floor(Math.random() * $('.quote').length);
while(true)
{
random = Math.floor(Math.random() * $('.quote').length);
if(random !== lastSelectedIndex) break;
}
$('.quote').eq(lastSelectedIndex).hide();
$('.quote').eq(random).fadeIn(500);
lastSelectedIndex = random;
}
})();
編輯:這是一個正在運行的示例
const changeQuote = (() => {
let lastSelectedIndex;
return function() {
let random = Math.floor(Math.random() * $('.quote').length);
while(true)
{
random = Math.floor(Math.random() * $('.quote').length);
if(random !== lastSelectedIndex) break;
}
$('.quote').eq(lastSelectedIndex).hide();
$('.quote').eq(random).fadeIn(500);
lastSelectedIndex = random;
}
})();
.quote {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="quote">Sentence 1</div>
<div class="quote">Sentence 2</div>
<div class="quote">Sentence 3</div>
<button onclick="changeQuote()">Show Random Quote</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/373259.html
標籤:javascript html 查询
