简体   繁体   中英

How to use jquery from parent inside an iframe?

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.

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?

Do note that this is not as usual access iframe/parent content from parent/iframe.

try this in the iframe:

if (typeof(jQuery) == "undefined") {
    var iframeBody = document.getElementsByTagName("body")[0];
    var jQuery = function (selector) { return parent.jQuery(selector, iframeBody); };
    var $ = jQuery;
}

Here is a better solution based on the Moin's answer:

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.

You need to load jQuery inside the iframe .

EDIT: Okay, if the frame is not on the same domain, then you do not have to reload jQuery. See Access jQuery library from iframe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM