我正在尝试修改此代码,以便单击按钮即可更改间隔时间,但我失败了。可以肯定的是,解决方案非常简单。感谢任何帮助。谢谢!
// define quotes array
var quotes = [
"AAAA",
"BBBB",
"CCCC"
];
// initialise current quote index
var quoteIndex = 0;
// get interval time
var interval = document.getElementById("interval").value;
// set target element
var $target = $('.container').find('h1');
// create timer function
var quoteTimer = function() {
// set target text to current quote
$target.fadeIn().text(quotes[quoteIndex]);
// increment the current index, or reset to 0 if on the last quote
quoteIndex = quoteIndex < quotes.length - 1 ? quoteIndex + 1 : 0;
}
// fire it up..!
$(document).ready(function() {
setInterval(quoteTimer, interval);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="interval" id="interval" value="" placeholder="Time" />
<input type="submit" name="button" id="button" value="Run" />
<div class="container">
<h1></h1>
</div>
最佳答案
我们将这段代码添加到您的代码中:
// Handle the button click to stop the current setInterval and to launch a new one
$('#button').click(() => {
clearInterval(intervalDescriptor);
intervalDescriptor = setInterval(quoteTimer, parseInt($('#interval').val(), 10));
});
// define quotes array
const quotes = [
"AAAA",
"BBBB",
"CCCC"
];
// initialise current quote index
let quoteIndex = 0;
// get interval time
const interval = document.getElementById("interval").value;
// set target element
const $target = $('.container').find('h1');
// create timer function
quoteTimer = function() {
// set target text to current quote
$target.fadeIn().text(quotes[quoteIndex]);
// increment the current index, or reset to 0 if on the last quote
quoteIndex = quoteIndex < quotes.length - 1 ? quoteIndex + 1 : 0;
}
let intervalDescriptor = false;
// Handle the button click to stop the current setInterval and to launch a new one
$('#button').click(() => {
clearInterval(intervalDescriptor);
intervalDescriptor = setInterval(quoteTimer, parseInt($('#interval').val(), 10));
});
// fire it up..!
$(document).ready(function() {
intervalDescriptor = setInterval(quoteTimer, interval);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="interval" value="" placeholder="Time" />
<input type="button" id="button" value="Run" />
<div class="container">
<h1></h1>
</div>
关于javascript - 单击按钮更改间隔时间Javascript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52366453/