Javascript 如何在 div 中动态插入 iframe
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3236430/
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
How do I dynamically insert an iframe in a div
提问by randomwebdev
How do I dynamically insert an iframe in a div using jQuery?
如何使用 jQuery 在 div 中动态插入 iframe?
$(document).ready(function() {
$("div").html("<iframe src='http://google.com'><iframe>");
});
I tried the above code, but it doesn't work.
我试过上面的代码,但它不起作用。
回答by Nick Craver
What you have works: http://jsfiddle.net/cUSVj/
你有什么作品:http: //jsfiddle.net/cUSVj/
Though keep in mind you can't do much with it after it's created if it's in not in the same domain, this is due to restrictions in place per the same-origin policy.
尽管请记住,如果它不在同一个域中,则在它创建后您不能对其进行太多操作,这是由于每个同源策略的限制。
Edit:I was closing the tag thinking it was a paste error, you are indeed missing a /in your </iframe>closing tag...this will/won't work depending on how generous the browser is. Make sure to close it correctly so your HTML is valid, otherwise you'll have cross-browser issues, ifit works to begin with.
编辑:我正在关闭标签,认为这是一个粘贴错误,您/的</iframe>结束标签中确实缺少一个...这将/不会起作用,具体取决于浏览器的慷慨程度。确保正确关闭它以使您的 HTML 有效,否则您将遇到跨浏览器问题,如果它开始工作。
回答by bodee
you did not close the iframe tag
你没有关闭 iframe 标签
<iframe>
</iframe>
回答by jeroen
I've used it like this and it works well ;-)
我已经像这样使用它并且效果很好;-)
$(".div").html("<iframe width='850' height='450' frameborder='0' scrolling='no' marginheight='0' marginwidth='0' src='http://yourlocation.com'></iframe>");
$(".div").css("display","block");
回答by James
The actual jquery code looks fine, you may not be referencing the div correctly i.e.
实际的 jquery 代码看起来不错,您可能没有正确引用 div,即
#div - would be an element with the id "div"
.div - would be an element with the class "div"
回答by Flakron Bytyqi
It works, I just tested it, what you might need is give jquery the id/class of the div you want to insert the iframe
它有效,我刚刚对其进行了测试,您可能需要为 jquery 提供要插入 iframe 的 div 的 id/class
eg. (id)
例如。(ID)
$("#myDiv").html("<iframe src='http://google.com'></iframe>");
eg. (class)
例如。(班级)
$(".myDiv").html("<iframe src='http://google.com'></iframe>");
回答by Krunal
Yes. It is working fine.
是的。它工作正常。
Check here : http://jsbin.com/arolo3/2/edit
在这里检查:http: //jsbin.com/arolo3/2/edit
You should close the iframe tag. It might be the issue.
您应该关闭 iframe 标记。这可能是问题所在。
回答by Tommy
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
$("#frameDiv").html("<iframe src='http://google.com'></iframe>");
});
</script>
<p>An IFrame should appear here</p>
<div id="frameDiv" style="width: 400px; height: 400px;"></div>
</body>

