2017-09-26 66 views
-2

我有一个带有按钮的网页。点击代码:在用document.write创建的文档中调用javascript函数

var html = ...html string containing visual and script elements... 
var view = window.open(); 
view.document.write(html); 
view.init(<parameters>); // see next code block 

HTML内容:

<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
    <style type="text/css"> 
     html, body { 
      height: 100%; 
      margin: 0; 
     } 
    </style> 
</head> 
<body> 
    <div id="id1"></div> 
    <script> 
     function init(<parameters>) { 
      ...work... 
     } 
    </script> 
</body> 
</html> 

问题是与Chrome的初始化函数调用:所有好,如果我在IE浏览器,但在铬我得到“INIT功能未定义“异常。 我应该怎么做才能在所有浏览器中都能正常工作?当然,我正在寻找一种不需要服务器往返的解决方案。

回答

-1

IM a noob so idk if this is exaclty true but but I read that ie ie you doot more chrome or firefox。这可能是其中一个例子,即你会做一些事情。

-1

如果不在同一个域中,则无法写入新窗口。我建议你可以在里面打开一个iframe。

How to write to iframe

How to write to page on same domain

+0

当然,您可以创建一个新窗口并写入它。当你这样做时,你正在创建一个虚拟文档。在这种情况下,域名不是问题。 –

+0

你说得对,我误解了这个问题。 –

0

使用document.write是实际可行的,当涉及到创造我想要的页面。问题是当我想调用在该页面内的JavaScript块中定义的函数时。不同的浏览器给出不同的结果,所以我想这是一个尚未完全标准化的问题。在互联网上有关于这方面的帖子,但我找不到一个明确和普遍的答案。 然后我用解决方法解决了我的僵局。最初的标记包含现在的参数占位符:

<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
    <style type="text/css"> 
     html, body { 
      height: 100%; 
      margin: 0; 
     } 
    </style> 
</head> 
<body> 
    <div id="id1"></div> 
    <script> 
     (init = function() { 
      var parameter1 = ${{placeholder1}} 
      var parameter2 = ${{placeholder2}} 
      ... 
      ...work... 
     })(); 
    </script> 
</body> 
</html> 

的创建代码,然后,替换占位符与实际值:

var html = ...html string containing placeholders... 
html = html.replace("${{placeholder1}}", actual1); 
html = html.replace("${{placeholder2}}", actual2); 
... 
var view = window.open(); 
view.document.write(html); 

现在初始化函数被调用在同一个页面的上下文,以及这也适用于Chrome。

相关问题