javascript - Iframe 每 X 秒更改一次 src

标签 javascript html iframe src

我正在尝试设置一个网页来查看我的工作的摄像头源。我们目前有 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/

相关文章:

javascript - 从 Rails Controller 中的 ajax 访问发布的 json 数据

javascript - 从一行后面显示两个文本元素

javascript - 如何清除特定 iframe 中的 setInterval

html - 将父页面链接链接到 iframe 中的 anchor

asp.net - mvc4 或 html 5 中的文件输入过滤器?

javascript - 突出显示 iframe 中的文本

javascript - 使用 observable - angular2 向所有订阅者元素发送数据

javascript - 如何防止点击通过固定定位元素传递到它后面的元素?

javascript - 从nodename和nodeindex获取html对象

javascript - 单击内部标签时将类添加到 li