2

在我的应用程序中,我每1000 毫秒调用一个方法来检查文档readyState。以下是我正在使用的代码:

var success=setInterval(""CheckState()"",1000);

function CheckState(){

if($get('businessDownl').document.readyState=="interactive" || 
      $get('businessDownl').document.readyState=="complete"){
           alert("Great");
           clearInterval(success);
  } 
}

此代码在 IE 浏览器中运行良好,但在 Firefox 和 Chrome 浏览器中失败。我也尝试使用 $get('businessDownl').readyState,它打印为未定义。谁能告诉我如何readyState在上述情况下使用 Firefox 和 Chrome?

4

2 回答 2

5

注意:为了能够访问 iframe 的文档并因此访问它readyState,您需要访问 iframe 中的域(不管使用 jQuery)。
有关更多信息,请查看此处


您可以使用 iframe 的contentWindow属性来完成(不需要 jQuery)。
请注意,为了访问 iframe document,您必须先将元素添加到 DOM(例如使用window.document.appendChild())。

示例代码:

var businessDownl = document.createElement('iframe');
document.body.appendChild(businessDownl);
...
var state = businessDownl.contentWindow.document.readyState;

另请参阅这个简短的演示
[在最新版本的 Firefox 和 Chrome 上测试。]

(请注意,由于 iframe 加载速度很快,有时您只会看到“已完成”,有时您会看到“正在加载”和“已完成”——我什至有幸看到“未初始化”:D)。

于 2013-05-22T11:04:48.257 回答
2

如果您只想等到文档准备好,则无需继续检查 - 您可以监听事件:

var whenReady = function(callback) {
  if (document.readyState === 'complete') callback(); // check not already loaded prior to this function being called
  else if (document.addEventListener) document.addEventListener('DOMContentLoaded', callback); // for standards compliant browsers (including IE 9+)
  else if (document.attachEvent) document.attachEvent('onreadystatechange', callback); // for IE 8
};

whenReady(alert('loaded'));

这种技术的唯一缺点是它只支持 IE 8 及更高版本。JQuery 等库提供更好的旧版浏览器支持和更简洁的语法:

$(function() {
  // anything here will execute once the dom is ready
});
于 2013-05-22T10:35:36.090 回答