Pass jquery variables between iframe and parent

2019-01-04 01:53发布

How can I work with jQuery and iframe. Get and pass var from iframe to body and from body to iframe. I have the following example. How can I click the button in iframe and make it take effect on the the body #test. How about ready var x in iframe.

<body>
var x = "whatever";
<div id"test"></div>
<iframe width="200px" height="200px" src="page.html"></iframe>
</body>

Inside page.html i have

<button>clickme</button>
<script>
var elm = $('<span>content</span>');
    elm.appendTo('#test')
</script>

3条回答
姐就是有狂的资本
2楼-- · 2019-01-04 01:59

From the parents perspective:

var iFrameValue = $('#iframe').get(0).contentWindow.myLocalFunction();

OR

var iFrameValue = $('#iframe').get(0).contentWindow.myLocalVariable;

From the iframe perspective

<script type="text/javascript">

var myLocalVariable = "hello";

function myLocalFunction () {
    return "hello";
}

</script>
查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-04 02:14

You can use contentWindow and contentDocument properties, if same origin poilicy is not a problem. I've setup a demo. View code for the demo and code for iframe.

查看更多
姐就是有狂的资本
4楼-- · 2019-01-04 02:18
$("#myid", top.document); 

or

$("#myid", parent.document.body); 

This will give you access to the container of the IFRAME

as per : http://groups.google.com/group/jquery-en/browse_thread/thread/5997ef4a60a123af

查看更多
登录 后发表回答