Adding IFRAME to DOM by Javascript

核能气质少年 提交于 2019-12-21 04:31:09

问题


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

回答1:


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.




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/6319514/adding-iframe-to-dom-by-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!