[英]Why does using document.write to create an iframe “cancel out” all remaining Javascript?
This happens in all browsers, so there must be a reason. 在所有浏览器中都会发生这种情况,因此一定有原因。
Example: 例:
<html>
<body>
<script>var a="support/";
var aa='<iframe src="http://google.com/' + a + '" />';
document.write(aa)</script>
<script>alert('test')</script>
</body>
</html>
The code after the iframe write (in this case alert('test')) doesn't execute. iframe写入后的代码(在本例中为alert('test'))不会执行。 Why?
为什么?
因为您正在将损坏的HTML写入文档-iframe标记上没有>。
Your HTML that you write into the document is invalid and causes the browser to fail interpreting the rest of the document, including the remaining <script>
tags. 您写入文档的HTML无效,并导致浏览器无法解释文档的其余部分,包括其余的
<script>
标记。
You are writing <iframe src="http://google.com/support/
. Add "></iframe>
and it's ok. 您正在编写
<iframe src="http://google.com/support/
。添加"></iframe>
。
However, a cleaner approach would be not to use document.write
at all (assuming you have some HTML element with id="container" to hold the iframe): 但是,更干净的方法是根本不使用
document.write
(假设您有一些ID为“ container”的HTML元素用于保存iframe):
var iframe = document.createElement('iframe');
iframe.setAttribute("src", "http://google.com/support/");
document.getElementById("container").appendChild(iframe);
You need to close your quotes and iframe. 您需要关闭引号和iframe。 This works:
这有效:
<html>
<body>
<script>var a="support/";
var aa='<iframe src="http://google.com/' + a + '" />';
document.write(aa)</script>
<script>alert('test')</script>
</body>
</html>
This code is Ok and working fine. 这段代码可以正常工作。 You can check it on JSFiddle Live DEMO .
您可以在JSFiddle Live DEMO上进行检查。 Rest you can edit it with your data..
休息吧,您可以使用您的数据进行编辑。
<script type="text/javascript">
var write_variable="p/about.html";
var write_iframe='<iframe src="http://www.exeideas.com/' + write_variable + '" />';
document.write(write_iframe);
</script>
Or you can check it online via HTML Editor And Previewer 或者您可以通过HTML编辑器和预览器在线检查它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.