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

查看:144
本文介绍了如何在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!在控制台上,但我看到未定义。现在,我的问题是我需要在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 / parent内容不同。

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天全站免登陆