我正在尝试在用户按下按钮时启动setInterval。按钮ID为#Begin。我已经尝试了各种方法,但是SetInterval根本无法使用。有什么办法可以使此工作?谢谢!
$(function () {
count = 0;
wordsArray = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5", "Text 6"];
setInterval(function () {
count++;
$(".first").fadeOut(400, function () {
$(this).text(wordsArray[count % wordsArray.length]).fadeIn(400);
});
}, 5000);
});
$(function () {
$('#begin').click(function(){
count = 0;
wordsArray = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5", "Text 6"];
setInterval(function () {
count++;
$(".first").fadeOut(400, function () {
$(this).text(wordsArray[count % wordsArray.length]).fadeIn(400);
});
}, 5000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="begin" value="Start" />
<div class="first">
</div>
javascript解决方案:
document.getElementById('button').addEventListener('click', function() {
setInterval(tick, 100);
});
function tick() {
console.log('tick');
}
jQuery可能看起来像这样:
$('#button').click(function() {
setInterval(tick, 100);
});
良好的做法是存储间隔,因此您可以在需要时清除它:
const interval = setInterval(tick, 100);
// Clear it this way
clearInterval(interval);
您使用jQuery,您可以添加回调以单击操作
$("#begin").click(function(event){
//start your timer like
var count = 0,
wordsArray = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5", "Text 6"];
setInterval(function () {
count++;
$(".first").fadeOut(400, function () {
$(this).text(wordsArray[count % wordsArray.length]).fadeIn(400);
});
}, 5000);
});
$('#begin').click(function(){
count = 0;
wordsArray = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5", "Text 6"];
setInterval(function () {
count++;
$(".text_display").fadeOut(400, function () {
$(this).text(wordsArray[count % wordsArray.length]).fadeIn(400);
});
}, 5000);
})
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<button id="begin">
Submit
</button>
<div class="text_display">
</div>