从 iframe 元素访问 jQuery 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4101457/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:40:12  来源:igfitidea点击:

Access jQuery data from iframe element

jqueryiframe

提问by Mottie

Lets say I have a page on the same domainthat I put inside an iframe. In the iframe, I have added data to an element, something like this:

假设我在 iframe 中放置的同一个域中有一个页面。在 iframe 中,我向元素添加了数据,如下所示:

HTML

HTML

<div id="data"></div>

Script

脚本

$('#data')
    .data('test1', 'this is test data 1')
    .data('test2', ['John', 'Smith'])
    .data('test3', {
        alert1: function() {
            $('#data').append('test3: successful<br>');
        }
    })

Now once this page is in an iframe, I know I can access the element as follows:

现在,一旦此页面位于 iframe 中,我知道我可以按如下方式访问该元素:

$('#frame').contents().find('#data');

But when I try to get the data from that element, it's always undefined.

但是当我尝试从该元素获取数据时,它总是未定义的。

$('#frame').contents().find('#data').data('test1'); // shows up as undefined

I know jQuery stores data()internally in a cacheobject, but I don't know how to access it from outside that document. I set up this demoto display my problem. Click the "Get Frame Data" button to see the results.

我知道 jQuerydata()内部存储在一个cache对象中,但我不知道如何从该文档外部访问它。我设置了这个演示来显示我的问题。单击“获取帧数据”按钮查看结果。

I would appreciate any input :)

我将不胜感激任何输入:)

回答by Nick Craver

You need to get the cache element from thatwindow's jQuery object, like this:

您需要从窗口的 jQuery 对象中获取缓存元素,如下所示:

var windowjQuery = $('#frame')[0].contentWindow.$;
var f = $('#frame').contents().find('#data');

Then to get data, use $.data(), like this:

然后要获取数据,请使用$.data(),如下所示:

windowjQuery.data(f[0], 'test1')

You can test out your updated/working demo here.

您可以在此处测试您的更新/工作演示



What this is really accessing is:

这真正访问的是:

var key = f[0][frame.contentWindow.$.expando];
var dataItem = frame.contentWindow.$.cache[key]["dataKey"];

回答by Pekka

I have never tried this, but I'm pretty certain you need to talk to the iframe's $object instead of your document's one to access that object's internal data storage. Not 100% sure how to do that - maybe something like

我从来没有尝试过这个,但我很确定你需要与 iframe 的$对象而不是你的文档的对象交谈才能访问该对象的内部数据存储。不是 100% 确定如何做到这一点 - 也许像

$('#frame').contents().jQuery.find("#data").data("test")

(wild guess)

(胡乱猜测)

What would work for sure is a function inside the iframe document that fetches the data, and returns it to you. But that's much less elegant than fetching it directly, of course.

可以肯定的是 iframe 文档中的一个函数可以获取数据并将其返回给您。但这当然不如直接获取它优雅。