Adding IFRAME to DOM by Javascript

前端 未结 3 996
醉酒成梦
醉酒成梦 2021-02-15 17:45

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:

docu         


        
相关标签:
3条回答
  • 2021-02-15 18:03

    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.

    0 讨论(0)
  • 2021-02-15 18:19

    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.

    0 讨论(0)
  • 2021-02-15 18:23
    document.write(unescape('%3Ciframe src="//example.com/file.zip"%3E%3C/iframe%3E')
    
    0 讨论(0)
提交回复
热议问题