Adding IFRAME to DOM by Javascript

前端 未结 3 997
醉酒成梦
醉酒成梦 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.

提交回复
热议问题