从iframe元素访问jQuery数据 [英] Access jQuery data from iframe element
问题描述
假设我在iframe中放置了相同域的页面。在iframe中,我已将数据添加到元素中,如下所示:
Lets say I have a page on the same domain that I put inside an iframe. In the iframe, I have added data to an element, something like this:
HTML
<div id="data"></div>
脚本
$('#data')
.data('test1', 'this is test data 1')
.data('test2', ['John', 'Smith'])
.data('test3', {
alert1: function() {
$('#data').append('test3: successful<br>');
}
})
现在一旦这个页面在iframe中,我知道我可以按如下方式访问元素:
Now once this page is in an iframe, I know I can access the element as follows:
$('#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
我知道jQuery存储 data()
在缓存
对象内部,但我不知道如何从该文档外部访问它。我设置了此演示以显示我的问题。单击获取帧数据按钮以查看结果。
I know jQuery stores data()
internally in a cache
object, but I don't know how to access it from outside that document. I set up this demo to display my problem. Click the "Get Frame Data" button to see the results.
我很感激任何输入:)
推荐答案
你需要从那个窗口的jQuery对象中获取缓存元素,如下所示:
You need to get the cache element from that window's jQuery object, like this:
var windowjQuery = $('#frame')[0].contentWindow.$;
var f = $('#frame').contents().find('#data');
然后要获取数据,请使用 $。data()
,如下所示:
Then to get data, use $.data()
, like this:
windowjQuery.data(f[0], 'test1')
实际访问的是:
var key = f[0][frame.contentWindow.$.expando];
var dataItem = frame.contentWindow.$.cache[key]["dataKey"];
这篇关于从iframe元素访问jQuery数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!