为何两个iframe加载顺序不同会导致功能异常?
问题分析:iframe搜索函数调用顺序导致功能失效
你遇到的核心问题是:调用两个iframe的搜索函数时,后调用的那个函数永远无法正常工作,问题根源出在错误使用了iframe.location.reload()这行代码。
问题原因拆解
- 当给iframe设置新的
src属性时,浏览器会自动发起新请求加载目标页面,完全不需要手动调用reload。 - 更关键的是:
iframe.location写法本身错误——正确获取iframe内部window对象的方式是iframe.contentWindow,直接访问iframe.location实际指向的是当前主页面的location对象! - 调用
iframe.location.reload()本质是在刷新主页面,主页面刷新会中断之前对第一个iframe的src修改操作,导致后执行的函数修改还没生效,页面就被重置,看起来像是后调用的函数没工作。
修复方案
直接删除两个搜索函数里的iframe_1.location.reload()和iframe_2.location.reload()代码即可。修改后的完整代码如下:
<body> <input type="text" id="txt_search" name="txt_search"> <button onclick="func_Search()">Search</button> <script> const iframe_1 = document.createElement("iframe"); iframe_1.src = "https://slovniky.lingea.cz/anglicko-cesky/"; iframe_1.setAttribute("width", window.innerWidth); iframe_1.setAttribute("height", window.innerHeight/2); iframe_1.style.top = "42px"; iframe_1.style.left = "0px"; iframe_1.frameBorder = "no"; iframe_1.scrolling = "yes"; iframe_1.style.position = "relative"; iframe_1.style.zIndex = "1000"; iframe_1.id = "iframe_1"; document.body.appendChild(iframe_1); const iframe_2 = document.createElement("iframe"); iframe_2.src = "https://prirucka.ujc.cas.cz/"; iframe_2.setAttribute("width", window.innerWidth); iframe_2.setAttribute("height", window.innerHeight/2); iframe_2.style.top = "0px"; iframe_2.style.left = "0px"; iframe_2.frameBorder = "no"; iframe_2.scrolling = "yes"; iframe_2.style.position = "relative"; iframe_2.style.zIndex = "1000"; iframe_2.id = "iframe_2"; document.body.appendChild(iframe_2); function func_Search (){ const search_text = document.getElementById('txt_search').value; func_Search_1(search_text); func_Search_2(search_text); } function func_Search_1 (search_text){ const iframe_1 = document.getElementById("iframe_1"); iframe_1.src = "https://slovniky.lingea.cz/anglicko-cesky/"+search_text; } function func_Search_2 (search_text){ const iframe_2 = document.getElementById("iframe_2"); iframe_2.src = "https://prirucka.ujc.cas.cz/?slovo="+search_text; } </script> </body>
额外提示
- 若确实需要手动刷新iframe(特殊场景),正确写法是
iframe.contentWindow.location.reload(),但前提是iframe的源与主页面同源,否则会触发跨域安全限制无法执行。 - 原代码中
search_text未用let/const声明,属于全局变量,建议加上const避免全局污染。
内容的提问来源于stack exchange,提问作者constantinuscz
相关产品推荐
相关产品推荐

