0

我正在尝试将 HTML 片段加载到以下新创建的 iframe 中。

<!DOCTYPE html>
<html>
<head><title>Test</title></head>
<body>
<script type="text/javascript">
    var iframeId = "frame"
            + Math.floor((Math.random() + "") * 1000000000000).toString();

    document.write('<iframe height="300"'
        + ' width="300"'
        + ' frameborder="0"'
        + ' scrolling="no"'
        + ' id="' + iframeId + '"'
        + ' name="' + iframeId + '"'
        + ' allowtransparency="true"></iframe>');

    var iframe = document.getElementById(iframeId);
    var iframeContent = '<!-- --\><script language=\"javascript\"\></script\>';
    iframe.contentWindow.document.open();

    iframe.contentWindow.document.write(
        '<!DOCTYPE html\><html\><head\><title\>Test</title\></head\><body\>'
        + iframeContent
        + '</body\></html\>');

    iframe.contentWindow.document.close();
</script>
</body>
</html>

当我在浏览器中打开此文档时,iframe 未正确加载。关于可能导致这种情况的任何想法?

如果我将 iFrameContent 设置为

var iframeContent = '<!-- --\>';

或者

var iframeContent = '<script language=\"javascript\"\></script\>';

该页面似乎正确加载。

iframeContent 本质上是第三方 HTML 片段(使用 freemarker js_string 转义)并且可能包含 HTML 注释。

4

2 回答 2

0

The problem is that the only way that the browser knows that your script section is done is to look for the "" tag, and you've got one of those right in the middle of your script. It thinks that that is the end of your javascript, and so of course that's a syntax error. It may also notice the "" tag, and think you have nested scripts. You can try something like this:

var iframeContent = '<!-- --\><' + 
    'script language=\"javascript\"\></' + 'script\>';

And see if that works.

Even better is to use something like document.createElement or the jQuery library to create your DOM elements.

于 2012-05-11T20:45:26.057 回答
0

看来,您的代码在 IE 中运行,但在其他浏览器中不运行。为了让它工作,你需要以某种方式转义开始评论的令牌,例如:

var iframeContent = '<!\-- --\><script language=\"javascript\"\></script\>';

结束</script\>-tag 在这里不是问题,因为它不是</script>代码中的文字。

于 2012-05-11T21:00:16.983 回答