简体   繁体   中英

.data() html5 cross window

I'm trying to put some data into a child windows html tag. But it doesn't seem to work. I tried putting it in with some jquery on that child window and that is working fine.

Here is the code implemented in the parent window to send the data to the child window:

$(".something", fullscreen.document).data("data1", "whatever");

Which will return "undefined" with the following jQuery code in the child window.

console.log($(".something").data("data1"));

But when I store the data with the child jQuery-script it works perfectly:

$(".something").data("data1", "whatever");

Is crosswindow data storing into tags not allowed?

jQuery does not save the data with the DOMElement but with in the scope the used jQuery instance . As of that two instances of jQuery no matter if in the same document (eg two versions of jQuery) or in different documents, won't share the internal data, neither they can access it.

You will always need retrieve the data with the same jQuery that was used to set it.

If you want to access the data in the child for an element where the data was that way:

$(".something", fullscreen.document).data("data1", "whatever");

then you would need to do it that way:

parent.window.$(".something", docmuent).data('data1');

jQuery uses its own data store for data you set with .data() . Each instance of jQuery (in each window) will have it's own separate data store so you won't get results from one when calling from another.

If your data is simply a string, then you will probably find it easier to not worry about multiple instance data stores and just use .attr() to store the string as an actual attribute on the DOM object. Then, there's zero question about where it's stored or how to access it because it's directly on the DOM object which you can easily get to from either jQuery instance.

// store data on the object
$(".something", fullscreen.document).attr("data-data1", "whatever");

// read data from within the target window
console.log($(".something").attr("data-data1"));

Note the use of the HTML5 "data-xxx" convention to avoid any attribute naming conflicts with standard attributes.

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