【问题标题】:After clearing document, document.write(ln) won't work?清除文档后,document.write(ln) 不起作用?
【发布时间】:2011-08-30 13:11:04
【问题描述】:

标题说我有问题,这里是例子:

...    
<script>
document.body.innerHTML = "";
document.write("<scr"+"ipt>alert(1);<\/scr"+"ipt>");
</script>

清空文件后,我想在里面写一些JS代码(当然我也想被执行)。我尝试了其他方法,但似乎它们不起作用(我有浏览器 Firefox 6.0)。

有没有人知道这个问题的解决方案或可行的替代方案?提前致谢!

【问题讨论】:

标签: javascript innerhtml document.write


【解决方案1】:

不要使用document.write()。只是不要。 (见Why is document.write considered a "bad practice"?


试试这个:

var text = 'alert(1);',
    script = document.createElement('script');
script.appendChild(document.createTextNode(text));
document.head.appendChild(script);

【讨论】:

    【解决方案2】:

    document.write 仅在加载 DOM 之前有效; document.body.innerHTML 仅在之后有效。

    尝试使用 document.body.appendChild 来追加一个新的文本节点。

    【讨论】:

    • 您可以访问document.body,即使 DOM 未完全解析(但仅在 body 内部而不在 head 内部)。
    • 嗯,这是一个不同的问题;)
    猜你喜欢
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多