javascript 如何在 iframe 中使用来自父级的 jquery?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10950034/
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 to use jquery from parent inside an iframe?
提问by Kumar
I have a file, let us call it parent-win.html, served by domain example.com. This file has jquery included in it. An iframe, lets call it iframe-win.html, is embedded in this page. iframe-win.html has a form element with id form-elem
and value Hello World!
. Now I do following inside iframe.
我有一个文件,我们称之为 parent-win.html,由域 example.com 提供。该文件中包含 jquery。一个 iframe,我们称之为 iframe-win.html,嵌入在这个页面中。iframe-win.html 有一个带有 idform-elem
和 value的表单元素Hello World!
。现在我在 iframe 中执行以下操作。
var jQuery = parent.jQuery;
console.log(jQuery('#form-elem').val());
According to my limited knowledge of JS I should see Hello World!
on console but instead I see undefined. Now, my question is do I need to load jquery again in an iframe or can I utilise jquery object already loaded in parent window?
根据我对 JS 的有限了解,我应该Hello World!
在控制台上看到,但我看到的是 undefined。现在,我的问题是我需要在 iframe 中再次加载 jquery 还是可以使用已经加载到父窗口中的 jquery 对象?
Do note that this is not as usual access iframe/parent content from parent/iframe.
请注意,这不像通常从父/iframe 访问 iframe/父内容。
回答by Moin Zaman
try this in the iframe:
在 iframe 中试试这个:
if (typeof(jQuery) == "undefined") {
var iframeBody = document.getElementsByTagName("body")[0];
var jQuery = function (selector) { return parent.jQuery(selector, iframeBody); };
var $ = jQuery;
}
回答by Andrey Shamakhov
Here is a better solution based on the Moin's answer:
这是基于 Moin 的答案的更好的解决方案:
if (typeof(jQuery) == "undefined") {
window.jQuery = function (selector) { return parent.jQuery(selector, document); };
jQuery = parent.$.extend(jQuery, parent.$);
window.$ = jQuery;
}
So we can use $'s functions like $.get, $.extends, etc.
所以我们可以使用 $ 的函数,如 $.get、$.extends 等。
回答by Thom Smith
You need to load jQuery inside the iframe
.
您需要在iframe
.
EDIT: Okay, if the frame is not on the same domain, then you do nothave to reload jQuery. See Access jQuery library from iframe
编辑:好的,如果帧是不在同一个域,那么你就不会重新加载jQuery的。请参阅从 iframe 访问 jQuery 库