javascript - How to share jQuery .data() data through iframe's? -
i'm trying share jquery data 1 or more iframe'd html pages parent html document. need inter-iframe communication , if possible (highly desireble) share/exchange .data() i.e. $.cache of both jquery objects (in parent , child iframe).
someting similar this:
parent html:
<!doctype html> <html> <head> <title >iframe-data</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" ></script> <script type="text/javascript" > jquery(function($){ var testdata = 'hello world #div1'; $('#div1').data('test',testdata); var newtestdata = $('.div2').closest('.div1').data('test'); $('#div2').append( 'parent window: "' + testdata + '" === "' + newtestdata + '" => ' + (testdata === newtestdata) ); }); // jquery() </script> </head> <body> <div id="div1" class="div1" > <div id="div2" class="div2" > </div> <iframe src="iframe-data2.html" ></iframe> </div> </body> </html>
iframe html:
<!doctype html> <html> <head> <title >iframe-data2</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" ></script> <script type="text/javascript" > jquery(function($){ var testdata = 'hello world #div1'; var $body = $(window.top.document.body); var $div1 = $body.find('#div1'); var outsidetestdata = $body.find('#div1').data('test'); var $div2 = $('#div2'); $div2.append( 'outside test data: "' + testdata + '" === "' + outsidetestdata + '" => ' + (testdata === outsidetestdata) ); }); // jquery() </script> </head> <body style="background-color: silver"> <div id="div1" class="div1" > <div id="div2" class="div2" > </div> </div> </body> </html>
jquery object created inside anonymous function , uses closure accessing global (global other jquery functions) array inside functions. so, result: jquery in iframe , jquery in top window have different data array. if need top level data, use window.top.jquery('#div1').data('test1')
(please note default context jquery document, created, using "top level jquery" don't need specify top level document.
Comments
Post a Comment