我正在尝试设置一个网页来查看我的工作的摄像头源。我们目前有 4 个摄像头,我们正在购买另一个。正如您所想象的那样,5 不会很好地适合网页。我找到了一个脚本,可以每隔 x 秒更改一次 iframe 的源,这样我就可以让我的一个 iframe 在两个提要之间来回切换。然而,此脚本导致源在两者每次轮换后更改为“未定义”。我错过了什么吗?
<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
的行中出现“差一个”错误。由于 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>
话虽如此,在我的测试中这实际上并没有导致旋转失败,但试试看......
关于javascript - Iframe 每 X 秒更改一次 src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46095254/