如何在 iframe 中使用来自父级的 jquery? [英] How to use jquery from parent inside an iframe?

查看:28
本文介绍了如何在 iframe 中使用来自父级的 jquery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,我们称之为 parent-win.html,由域 example.com 提供.该文件中包含 jquery.一个 iframe,我们称之为 iframe-win.html,嵌入在这个页面中.iframe-win.html 有一个表单元素,id 为 form-elem,值为 Hello World!.现在我在 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());

根据我对 JS 的有限了解,我应该在控制台上看到 Hello World! 但我看到的是 undefined.现在,我的问题是我需要在 iframe 中再次加载 jquery 还是可以使用已经加载到父窗口中的 jquery 对象?

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?

请注意,这不像往常那样从父/iframe 访问 iframe/父内容.

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

推荐答案

在 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;
}

这篇关于如何在 iframe 中使用来自父级的 jquery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆