使用"开始"和"停止"按钮循环访问 url 列表



我有一个URL列表,我需要它在"开始"one_answers"停止"按钮上以幻灯片形式运行。目前,它以幻灯片的形式运行,没有启动和停止按钮。

此外,我需要设计一个主页与所有这些URL的缩略图。点击缩略图,它必须重定向到该页面

<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(function () {
var urls = ["URL1", "URL2", "URL3","URL4", "URL5", "URL6","URL7", "URL8", "URL9"];
var i = 0;
function loadIframe(url)
{
$('#iframe').attr('src', url);
}
setInterval(function() {
// update the index
i = (i + 1) % urls.length; 
loadIframe(urls[i]); 
}, 13000);
loadIframe(urls[i]); 
});
</script>
</head>
<body>
<iframe id="iframe" height="100%" width="100%"></iframe>
</body>
</html>

您需要触发setInterval并保存它,以便稍后清除它。

var intvl = false; //Global Variable
$('#StartButton').on('click', function() 
{ 
(!intvl) ? intvl = setInterval(...) : return; 
});
$('#StopButton').on('click', function() 
{ 
clearInterval(intvl);
intvl = false;
});

编辑:更改为禁用多个间隔

您可以通过将setInterval存储在变量中,以便在其上使用clearInterval()来实现这一点。clearInterval()将允许您停止/暂停创建的setInterval

您也不再需要$(function() {...})组件,因为您将控制滑块何时启动/停止:

var slideInterval;
var urls = ["URL1", "URL2", "URL3", "URL4", "URL5", "URL6", "URL7", "URL8", "URL9"];
var i = 0;
function loadIframe(url) {
//$('#iframe').attr('src', url);
$('#iframe').html(url);
}
function start() {
if (!slideInterval) { // If an interval is already in-use (ie if the slider is running) don't allow another slider to be made -> continue using the current one.
slideInterval = setInterval(function() {
// update the index
i = (i + 1) % urls.length;
loadIframe(urls[i]);
}, 1000);
}
}
function stop() {
if (slideInterval) { // If an interval doe exsist, we can then clear it, if it doesn't exsist then we have no interval to "clear", and so we don't run this code if one isn't in use
clearInterval(slideInterval);
slideInterval = null;
}
}
loadIframe(urls[0]);
#iframe {
border: 1px solid black;
}
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<div id="iframe" height="100%" width="100%"></div>
<button onclick="start()">Start</button>
<button onclick="stop()">Stop</button>

最新更新