简体   繁体   English

通过 Javascript 将 IFRAME 添加到 DOM

[英]Adding IFRAME to DOM by Javascript

I want to add an iframe to the page.我想在页面上添加一个iframe This iframe should refer to a URL.iframe应参考 URL。 I added the below code to page HTML, but it doesn't work:我将以下代码添加到页面 HTML,但它不起作用:

document.createElement('<iframe src='http://example.com'></iframe>');

Here you go:这里是 go:

var iframe;

iframe = document.createElement('iframe');
iframe.src = 'http://example.com/file.zip';
iframe.style.display = 'none';
document.body.appendChild(iframe);

Live demo: http://jsfiddle.net/USSXF/2/现场演示: http://jsfiddle.net/USSXF/2/

Your code doesn't work because you're passing an entire HTML string into the createElement function ("jQuery style" :) ), which is invalid.您的代码不起作用,因为您将整个 HTML 字符串传递到createElement function ("jQuery style" :) ),这是无效的。 The valid parameter for this function is a string representing the tag-name (like 'div' , 'iframe' , 'p' , etc.).此 function 的有效参数是表示标记名称的字符串(如'div''iframe''p'等)。

Read about document.createElement here. 在此处阅读有关document.createElement的信息。

You need to append the node to the DOM using document.appendChild您需要使用document.appendChild将 append 节点添加到 DOM

You also need to escape your inner single-quotes or use double-quotes instead.您还需要转义内部单引号或使用双引号。

document.write(unescape('%3Ciframe src="//example.com/file.zip"%3E%3C/iframe%3E')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM