Adding an iframe by JAVASCRIPT

Adding an iframe by JAVASCRIPT

本文关键字:JAVASCRIPT by iframe an Adding      更新时间:2023-09-26

我试图通过javascript获得添加iframe的javascript。它在标签前创建iframe

你可以看到jsfiddle demo。但是我不想添加标签。我只是想添加外部。js文件,它自己做所有的事情!

使用

var newElem = createElement('script');
newElem.setAttribute('src',      'http://example.com/js/script.js');
newElem.setAttribute('type',     'text/javascript');
newElem.setAttribute('language', 'JavaScript');
document.getElementById('IdFromTheHeadElem').appendChild(newElem);

可以用

创建标签

document.write("<iframe..............>");

编辑:解决方案我写在jQuery的评论:

在JS文件中:

$(function(){
    $('#container').html('<iframe........');
});

在你的HTML中:

<div id="#container"></div>

用:

<script src=".............yourscriptname.js"></script>

从你的jsfiddle看来,你应该这样做(在纯JS中),以避免在HTML代码中直接定义iframe:

var iframe = document.createElement('iframe');
iframe.id = 'iframeID';
document.body.appendChild(iframe);
// the rest is manipulating this iframe
iframe.contentDocument.write("<html><head></head><body><div id='foo'>The div</div></body></html>");
iframe.contentDocument.getElementById('foo').innerHTML = "Greetings from outside!";
jsfiddle上的

代码(我将那里的代码包装在闭包中,以防止污染全局命名空间)

document.body.appendChild(iframe);应该改变为其他东西取决于你想把它放在页面内的地方(例如document.getElementById('some-div-id').appendChild(iframe);)