记录一个坑,页面使用iframe想要动态加载内容,代码如下,但是“test"总会输出两次,后来找到了原因,是iframe的src导致页面重复加载所以js加载了两次;
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
<meta charset="UTF-8">
<title>view</title>
</head>
<body style="width: 100%;height: 100%;" >
<iframe id="iframe1" src=#></iframe>
<div id="two" style="display: none">
<iframe id="iframe2" src=#></iframe>
</div>
</div>
<script>
console.log("test")
</script>
</body>
</html>
解决办法:
将src属性删掉,js里直接动态绑定,这样就不会在加载页面时重复执行js,
<body style="width: 100%;height: 100%;" >
<iframe id="iframe1" src=#></iframe>
<div id="two" style="display: none">
<iframe id="iframe2" src=#></iframe>
</div>
</div>
<script>
console.log("test")
var iframe1 = document.getElementById('iframe1');
var iframe2 = document.getElementById('iframe2');
iframe1.src = "path1";
iframe2.src = "path2";
</script>
</body>
文章讲述了在HTML中使用iframe动态加载内容时遇到的问题,即由于src属性导致页面加载时JS执行两次。解决方法是删除src属性,用JavaScript直接设置IFrame的src。



1440

被折叠的 条评论
为什么被折叠?



