javascript 如何将文档内容动态加载到 iframe 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4399417/
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 11:17:10  来源:igfitidea点击:

How to dynamic load the document content into an iframe?

javascripthtmlcssiframe

提问by Tattat

I would like to make something like this

我想做这样的事情

|--------------------------|
|                A         |
|        ____________      |
|       |            |     |
|       |            |     |
|       |      B     |     |
|       |            |     |
|       |____________|     |
|                          |
|__________________________|

The B page is inside the A page, and I want to insert all the js, css, into the A page, and I want to separate the B page, and I design it to use a iFrame, and get the b page dynamically. But if I use the src in the B page iframe, the A page js, css can't control it... How can I exactly insert all the B page code inside the A page, but don't need copy&paste all the code from B page to A page? Thank you.

B页在A页里面,我想把所有的js、css都插入到A页中,我想把B页分开,我设计成使用iFrame,动态获取b页。但是如果我在B页iframe中使用src,A页js、css控制不了...如何将B页代码全部插入A页内,而不需要copy&paste所有代码从 B 页到 A 页?谢谢你。

回答by Vincent Ramdhanie

You may want to look at an AJAX solution. This way you avoid the iframe and associated complexity. On the A page you can create a div tag with a specific id. Then using AJAX you can load the content of the B page into the div tag.

您可能想查看 AJAX 解决方案。这样您就可以避免 iframe 和相关的复杂性。在 A 页面上,您可以创建具有特定 id 的 div 标签。然后使用 AJAX 可以将 B 页面的内容加载到 div 标签中。

The HTML that is loaded can then directly be manipulated by the code on your A page since it is essentially one page.

加载的 HTML 可以直接由 A 页面上的代码操作,因为它本质上是一个页面。

If you are using plain javascript then you will find all the info you need in this tutorial.

如果您使用的是纯 javascript,那么您将在本教程中找到您需要的所有信息。

If on the other hand you wish to use jQuery then it is as simple as:

另一方面,如果您希望使用 jQuery,那么它很简单:

  $('#myDiv').load('B.html');

where myDiv is the ID of your div.

其中 myDiv 是您的 div 的 ID。

回答by Stijn Van Antwerpen

$('#iframeId').contents().find('html').html(yourContent);