Iframe 每 X 秒更改一次 src

Iframe changing src every X seconds

我正在尝试设置一个网页来查看我的工作的摄像头源。我们目前有 4 个摄像头,我们正在购买另一个。正如您所想象的那样,5 不会很好地适合网页。我找到了一个脚本来每隔 x 秒更改 iframe 的源,这样我就可以让我的 iframe 之一在两个提要之间来回切换。然而,此脚本导致源在两者每次轮换后更改为 'undefined'。我错过了什么吗?

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Live Camera Feed</title>
<link rel="stylesheet" href="style.css">

<script type="text/javascript">
var links = ["https://192.168.10.123/NW_Corner/push.php","https://192.168.10.123/NE_Corner/push.php"];
var i = 0;
var renew = setInterval(function(){
    document.getElementById("frame").src = links[i];        
    if(links.length == i){
        i = 0;
    }
    else i++;
},5000);
</script>

</head>
<body>

<table width="75%" height="75%">
    <tr>
        <td><iframe width="1280" height="720" src="https://192.168.10.123/Driveway/push.php" width="75%" height="75%"></iframe></td>
        <td><iframe width="1280" height="720" src="https://192.168.10.123/South_Door/push.php" width="75%" height="75%"></iframe></td>
    </tr>
    <tr>
        <td><iframe id="frame" width="1280" height="720" src="https://192.168.10.123/NW_Corner/push.php" width="75%" height="75%"></iframe></td>
        <td><iframe width="1280" height="720" src="https://192.168.10.123/NE_Corner/push.php" width="75%" height="75%"></iframe></td>
    </tr>
</table>
</body>
</html>

您在检查 links.length 的那一行有一个 "off by one" 错误。由于 JS 数组是从零开始的,因此长度总是比最后一个元素多一个 - 即在你的情况下你有元素零和一个,但长度是两个。

所以你的支票应该是 if(links.length - 1 == i) 像这样:

var links = ["https://192.168.10.123/NW_Corner/push.php","https://192.168.10.123/NE_Corner/push.php"];
var i = 0;
var renew = setInterval(function(){
    document.getElementById("frame").src = links[i];        
    if(links.length - 1 == i){
        i = 0;
    }
    else i++;
},5000);
<table width="75%" height="75%">
    <tr>
        <td><iframe width="1280" height="720" src="https://192.168.10.123/Driveway/push.php" width="75%" height="75%"></iframe></td>
        <td><iframe width="1280" height="720" src="https://192.168.10.123/South_Door/push.php" width="75%" height="75%"></iframe></td>
    </tr>
    <tr>
        <td><iframe id="frame" width="1280" height="720" src="https://192.168.10.123/NW_Corner/push.php" width="75%" height="75%"></iframe></td>
        <td><iframe width="1280" height="720" src="https://192.168.10.123/NE_Corner/push.php" width="75%" height="75%"></iframe></td>
    </tr>
</table>

话虽如此,在我的测试中这实际上并没有导致旋转失败,但试试看...