开发者

Adding IFRAME to DOM by Javascript

I want to add an iframe to the page. This iframe should refer to a URL. I added the below code to page HTML, but it doesn't work:

document.createElement('<iframe src='ht开发者_如何学JAVAtp://example.com'></iframe>');


Here you 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/

Your code doesn't work because you're passing an entire HTML string into the createElement function ("jQuery style" :)), which is invalid. The valid parameter for this function is a string representing the tag-name (like 'div', 'iframe', 'p', etc.).

Read about document.createElement here.


You need to append the node to the DOM using document.appendChild

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')
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜