确切的问题是如何使用纯JavaScript不使用jQuery做。
我一直使用可以在jQuery的源代码中找到了解决办法。 这只是一行和纯JavaScript。
对我来说这是最好的,甚至得到I帧内容的最短途径。
首先让你的iframe:
var iframe = document.getElementById('id_description_iframe');
// or
var iframe = document.querySelector('#id_description_iframe');
然后使用jQuery的解决方案:
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
它的工作原理,即使在Internet Explorer中该iframe
对象的contentWindow
财产过程中做到这一点伎俩。大多数其他浏览器使用contentDocument
属性,这就是为什么我们在此OR条件中首先证明此属性的原因。如果没有设置,请尝试contentWindow.document
。
然后通常可以使用getElementById()
甚至querySelectorAll()
从一个iframeDocument
选择DOM的元素:
var iframeContent;
if (iframeDocument) {
iframeContent = iframeDocument.getElementById('frameBody');
// or
iframeContent = iframeDocument.querySelectorAll('#frameBody');
}
通话功能在iframe
从得到公正的window
元素iframe
来调用一些全局函数,变量或整个库(例如jQuery
):
var iframeWindow = iframe.contentWindow;
if (iframeWindow) {
// 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.inside_iframe_variable = window.outside_iframe_variable;
// or call a global function
var myReturnValue = iframeWindow.globalFunction(withParam);
}
注意
这一切,如果你观察same-origin policy是可能的。
重要注意事项:如果iFrame的内容是跨域的,则无法访问它。参见[同源策略](http://en.wikipedia.org/wiki/Same-origin_policy)。 – 2014-01-01 01:42:05