使用“开始”和“停止”按钮遍历网址列表

时间:2018-11-28 09:25:53

标签: javascript jquery html

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

另外,我需要设计一个包含所有这些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>

2 个答案:

答案 0 :(得分:0)

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

file_Mo

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

答案 1 :(得分:0)

您可以通过将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>