确切的问题是如何使用纯 JavaScript 而不是 jQuery。
但我总是使用可以在 jQuery 的源代码中找到的解决方案。
这只是一行原生 JavaScript。
对我来说,这是获取 iframe 内容的最佳、易读甚至 afaik 最短的方法。
首先获取您的 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。
选择 iframe 中的元素
那么您通常可以使用getElementById() 甚至querySelectorAll() 从iframeDocument 中选择DOM-Element:
if (!iframeDocument) {
throw "iframe couldn't be found in DOM.";
}
var iframeContent = iframeDocument.getElementById('frameBody');
// or
var iframeContent = iframeDocument.querySelectorAll('#frameBody');
在 iframe 中调用函数
仅从iframe 中获取window 元素以调用一些全局函数、变量或整个库(例如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 /*, ... */);
注意
如果您观察same-origin policy,这一切皆有可能。