2013-03-26 84 views
0

我尝试在对象元素(type =“text/html”)内调用document.open/write/close序列。在Safari/Chrome中,我可以通过contentDocument属性获取内部文档对象。示例代码(使用jQuery):JavaScript:如何检索HTML对象标签的文档对象?

$(document).ready(function() { 
    var container = $('<object/>') 
    .css({'width': '700px', 'height': '100px', 'border': '0px none'}) 
    .attr({'type': 'text/html'}).appendTo('body'); 

    var doc = container.get(0).contentDocument; 
    doc.open(); 
    doc.write('<h1>Hello world!</h1>'); 
    doc.close(); 
}); 

有没有办法做到在其他浏览器一样的吗?

我想做这种奇怪的事情的原因是我需要在DOM关闭后调用包含document.write的外部脚本。我已经尝试过处理iframe,但是由于Internet Explorer和Opera错误,我失败了。任何其他方式来实现这一目标将不胜感激。

+0

什么错误?并且该对象的src是最初相同的原点吗? – mplungjan 2013-03-26 18:05:10

+0

http://stackoverflow.com/questions/1736886/why-wont-this-javascript-using-document-open-and-document-write-work-in-inter Bobince评论解释了错误。 IE9仍然受到影响,最终可能会崩溃。 – pamelus 2013-03-26 18:15:22

回答

1

这应该适合你。我不知道为什么(我只有我的怀疑)。

$(document).ready(function() { 
    var container = $('<object>') 
     .css({ 
      'width': '700px', 
      'height': '100px', 
      'border': '0 none' 
     }) 
     .attr({ 
      'type': 'text/html', 
      'data': 'about:blank' 
     }) 
     .appendTo('body'); 

    function writeToDoc() { 
     var obj, doc; 
     obj = container.get(0); 
     if (obj.document) { 
      doc = obj.document; 
     } else if (obj.contentWindow) { 
      doc = obj.contentWindow.document; 
     } 
     else if (obj.contentDocument) { 
      doc = obj.contentDocument; 
     } 
     if (doc) { 
      doc.open(); 
      doc.write('<h1>Works!</h1>'); 
      doc.close(); 
     } else { 
      $('body').append('<h1>No luck...</h1>'); 
     } 
    }; 

    // yes, this is weird 
    setTimeout(writeToDoc, 0); 
}); 
1

对象元素在HTML5中已弃用,因此您将无法再执行此操作。