我试图在用户按下按钮时启动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);
});
答案 0 :(得分:3)
$(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>
&#13;
答案 1 :(得分:0)
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);
答案 2 :(得分:0)
您使用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);
});
答案 3 :(得分:0)
$('#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);
})
&#13;
<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>
&#13;