最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

asp.net - Adding IFRAME to DOM by Javascript - Stack Overflow

programmeradmin2浏览0评论

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=''></iframe>');

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='http://example.com'></iframe>');
Share Improve this question edited Jun 12, 2011 at 1:40 Xaqron asked Jun 12, 2011 at 1:13 XaqronXaqron 30.9k44 gold badges145 silver badges211 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 17

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)

  1. 暂无评论