javascript 是否可以使用javascript单击按钮创建iframe

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5335321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:51:43  来源:igfitidea点击:

Is it possible to create an iframe on click of a button using javascript

javascripthtmliframe

提问by user475685

I have a UI with a print button, i want to create an iframe on click of the print button, is it possible using javascript?

我有一个带有打印按钮的 UI,我想在单击打印按钮时创建一个 iframe,是否可以使用 javascript?

采纳答案by alex

document.getElementById('print-button').onclick = function() {

   var iframe = document.createElement('iframe');
   iframe.src = 'http://example.com';
   document.body.appendChild(iframe);

};

Of course, if you're intending to attach more events of the same type, use addEventListener().

当然,如果您打算附加更多相同类型的事件,请使用addEventListener().

If jQuery is at your disposal...

如果您可以使用 jQuery...

$("#print-button").click(function() {
    $("<iframe />", { src: "http://example.com" }).appendTo("body");
});

回答by Jeremy Conley

Sure...#printbutton is the ID of your print button.

当然...#printbutton 是您的打印按钮的 ID。

<a href="#" id="printbutton">Print</a>
<div id="iframe_parent"></div>

<script src="PATH-to-JQUERY"></script>
<script>
$('#printbutton').click(function(){
var iframe = document.createElement('iframe');
iframe.setAttribute('src', 'path/to/iframe/page/');
document.getElementById('iframe_parent').appendChild(iframe);
});
</script>

回答by Pankaj Tiwari

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
    $('#button').click(function(){
        if(!$('#iframe').length) {
                $('#iframeHolder').html('<iframe id="iframe" src="http://w3schools.com" width="700" height="450"></iframe>');
        }
    });   
});
</script>

<a id="button">Button</a>
<div id="iframeHolder"></div>