有多个<iframe>标签,如果要实现刷新页面随机生效某一个应该怎么写
时间: 2024-02-09 09:10:28 浏览: 70
您可以为每个 <iframe> 元素生成一个随机数,然后将其作为查询字符串添加到其 src 属性中。这样每次刷新页面时,就会随机选择一个 <iframe> 加载。以下是示例代码:
```html
<iframe src="https://example.com/page1.html?random=123"></iframe>
<iframe src="https://example.com/page2.html?random=456"></iframe>
<iframe src="https://example.com/page3.html?random=789"></iframe>
<script>
// 生成随机数
var randomNum = Math.floor(Math.random() * 1000);
// 获取所有 <iframe> 元素
var iframes = document.getElementsByTagName('iframe');
// 遍历 <iframe> 并添加随机数到 src 属性中
for (var i = 0; i < iframes.length; i++) {
var src = iframes[i].getAttribute('src');
iframes[i].setAttribute('src', src + '?random=' + randomNum);
}
</script>
```
请注意,此代码仅适用于同源的 <iframe>。如果您的 <iframe> 来自不同的域,则需要在服务器端设置 CORS 头文件才能使其正常工作。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![text/plain](https://img-home.csdnimg.cn/images/20250102104920.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)