问题描述
< iframe id =id_description_iframeclass =rte-zoneheight =200frameborder =0title =description>
< html>
< head>< / head>
< body class =frameBody>
测试< br />
< / body>
< / html>
< / iframe>
我想要的是:
试验<峰; br />
确切的问题是如何使用纯JavaScript而不是jQuery。
但我总是使用可以在jQuery源代码中找到的解决方案。
这只是一行本地JavaScript。
对我来说,它是最好的,易读的,甚至是 afaik
首先获取您的iframe
var iframe = document.getElementById('id_description_iframe');
//或
var iframe = document.querySelector('#id_description_iframe');
然后使用jQuery的解决方案
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
选择iframe中的元素
然后您通常可以使用 getElementById()
甚至 querySelectorAll()
从 iframeDocument
中选择DOM元素:
<$ p $如果(!iframeDocument){
throw在DOM中找不到iframe。
}
var iframeContent = iframeDocument.getElementById('frameBody');
//或
var iframeContent = iframeDocument.querySelectorAll('#frameBody');
在iframe中调用函数
$ b
从 iframe
获取窗口
元素来调用一些全局函数,变量或整个库(例如 jQuery
):
var iframeWindow = iframe.contentWindow;
//你甚至可以调用jQuery或其他框架
//如果在iframe中加载
iframeContent = iframeWindow.jQuery('#frameBody');
//或
iframeContent = iframeWindow。$('#frameBody');
//甚至可以使用任何其他全局变量
iframeWindow.myVar = window.myVar;
//或调用全局函数
var myVar = iframeWindow.myFunction(param1 / *,... * /);
注意
如果您观察,所有这一切都是可能的。
<iframe id="id_description_iframe" class="rte-zone" height="200" frameborder="0" title="description">
<html>
<head></head>
<body class="frameBody">
test<br/>
</body>
</html>
</iframe>
What I want to get is:
test<br/>
The exact question is how to do it with pure JavaScript not with jQuery.
But I always use the solution that can be found in jQuery's source code.It's just one line of native JavaScript.
For me it's the best, easy readable and even afaik the shortest way to get the iframes content.
First get your iframe
var iframe = document.getElementById('id_description_iframe');
// or
var iframe = document.querySelector('#id_description_iframe');
And then use jQuery's solution
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
Select elements in iframe
Then you can usually use getElementById()
or even querySelectorAll()
to select the DOM-Element from the iframeDocument
:
if (!iframeDocument) {
throw "iframe couldn't be found in DOM.";
}
var iframeContent = iframeDocument.getElementById('frameBody');
// or
var iframeContent = iframeDocument.querySelectorAll('#frameBody');
Call functions in the iframe
Get just the window
element from iframe
to call some global functions, variables or whole libraries (e.g. jQuery
):
var iframeWindow = iframe.contentWindow;
// you can even call jQuery or other frameworks
// if it is loaded inside the iframe
iframeContent = iframeWindow.jQuery('#frameBody');
// or
iframeContent = iframeWindow.$('#frameBody');
// or even use any other global variable
iframeWindow.myVar = window.myVar;
// or call a global function
var myVar = iframeWindow.myFunction(param1 /*, ... */);
Note
All this is possible if you observe the same-origin policy.
这篇关于如何在JavaScript中获取iframe的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!