开发者

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>开发者_如何学JAVA;alert('test')</script>
</body>
</html>

The code after the iframe write (in this case alert('test')) doesn't execute. Why?


Because you're writing broken HTML into the document -- there's no > on the iframe tag.


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.

You are writing <iframe src="http://google.com/support/. Add "></iframe> and it's ok.

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):

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. 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. 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜