Access elements of parent window from iframe

2019-01-03 06:20发布

I have a page we can call parent.php. In this page i have an iframe with a submit form and outside of that i have a div with the id "target". Is it possible to submit the form in the iframe and when success refresh the target div. Say load a new page into it or something?

Edit: The target div is in the parent page, so my question is basicly if you can make for an example a jquery call outside the iframe to the parent. And how that would look?

Edit 2: So this is how my jquery code looks like now. It is in the of the iframe page. the div #target is in the parent.php

$(;"form[name=my_form]").submit(function(e){     
 e.preventDefault; 
 window.parent.document.getElementById('#target'); 
 $("#target").load("mypage.php", function() { 
 $('form[name=my_form]').submit(); 
 }); 
 })

I dont know if the script is active cause the form submits succcessfully but nothing happens to target.

Edit 3:

Now im trying to call the parent page from a link within the iframe. And no success there either

<a href="javascript:window.parent.getElementById('#target').load('mypage.php');">Link</a>

4条回答
淡お忘
2楼-- · 2019-01-03 06:42

Have the below js inside the iframe and use ajax to submit the form.

$(function(){

   $("form").submit(e){
        e.preventDefault();

       //Use ajax to submit the form
       $.ajax({
          url: this.action,
          data: $(this).serialize(),
          success: function(){
             window.parent.$("#target").load("urlOfThePageToLoad");
          });
       });

   });

});
查看更多
放荡不羁爱自由
3楼-- · 2019-01-03 06:49

You can access elements of parent window from within an iframe by using window.parent like this:

// using jquery    
window.parent.$("#element_id");

Which is the same as:

// pure javascript
window.parent.document.getElementById("element_id");

And if you have more than one nested iframes and you want to access the topmost iframe, then you can use window.top like this:

// using jquery
window.top.$("#element_id");

Which is the same as:

// pure javascript
window.top.document.getElementById("element_id");
查看更多
Explosion°爆炸
4楼-- · 2019-01-03 07:04

I think you can just use window.parent from the iframe. window.parent returns the window object of the parent page, so you could do something like:

window.parent.document.getElementById('yourdiv');

Then do whatever you want with that div.

查看更多
狗以群分
5楼-- · 2019-01-03 07:09

I think the problem may be that you are not finding your element because of the "#" in your call to get it:

window.parent.document.getElementById('#target'); 

You only need the # if you are using jquery. Here it should be:

window.parent.document.getElementById('target'); 
查看更多
登录 后发表回答