【发布时间】:2015-04-25 23:50:32
【问题描述】:
我正在动态创建 iframe 以显示通过 url 获得的文档。每个文档都在一个 iframe 中,而 iframe 又在一个 div 中。我有一个标签栏,它允许显示任何文档,同时隐藏其余文档,这是一个典型的标签页。
我想显示包含接收第一个响应的 iframe 的 div,即显示第一个加载并隐藏其余部分。无法预测哪个会先加载,所以我需要一种方法来检测第一个并显示它并隐藏所有其余部分。
我想我可以通过让 iframe onload 函数检查一个在第一个 onload 处理程序运行时设置为 true 的全局布尔值来做到这一点。
我不知道为什么,但这感觉很容易出错。有一个更好的方法吗?
var firstDocumentReceived = false ;
function buildFileTabs(evt) {
firstDocumentReceived = false ;
var files = evt.target.files; // files is a list of File objects.
for (var i = 0, f; f = files[i]; i++) {
addTab ( files[i].name );
}
// create a div to display the requested document
function addTab ( fileName ) {
var newDiv = document.createElement("div");
newDiv.id = fileName.replace(".","_") + newRandomNumber() ;
// create an iframe to place in the div
var newIframe = document.createElement("iframe");
newIframe.onload=iframeLoaded ;
newIframe.setAttribute("seamless", true );
newIframe.setAttribute("div_id" , newDiv.id) ;
newIframe.src = url ; // the iframe will contain a web page returned by the FDS server
// nest the iframe in the div element
newDiv.appendChild(newIframe) ;
// nest the div element in the parent div
document.getElementById("documentDisplay").appendChild(newDiv) ;
...
function iframeLoaded ( event ) {
if ( firstDocumentReceived === false ) {
firstDocumentReceived = true ;
// show the div associated with this event
} else {
// hide the div associated with this event
}
【问题讨论】:
-
你控制 iframe 的内容吗?
-
乔,不知道你在问什么。 iframe 内容由服务器返回,但我不知道内容是什么。我只知道传递给服务器的文件名。
-
如果你可以使用 ES6(或 Promise polyfill),这就是
Promise.race设计的问题。 -
@joews,这是一个好方法。 @user903724,我修改了我的答案,包括如何使用 ES6
Promise.race()。
标签: javascript html iframe