Target parent div containing iframe from iframe

2020-07-18 05:17发布

问题:

So basically I have something like this

<div class="iframe-holder">
    <span></span>
    <iframe src="iframe.html" width="200" height="200"
</div>
<div class="iframe-holder">
    <span></span>
    <iframe src="iframe.html" width="200" height="200"
</div>
<div class="iframe-holder">
    <span></span>
    <iframe src="iframe.html" width="200" height="200"
</div>
<script>
    function where_am_i(iframe_parent_div,msg){
        $(iframe_parent_div).find('span').html(msg);
    }
</script>   

and then in my iframe-holder.html I basically have this

<a href="#" id="msg">Show Message In Parent Div</a>
<script>
    //i want to basically imp
    $('msg').click(function(event){
        event.preventDefault();
        var iframe_parent_div=???;//how do I get this?
        parent.where_am_i(iframe_parent_div,'This is where this iframe is');
    });     
</script>

So basically my question is how can I target the parent div (div.iframe-holder) of the iframe instance I am clicking the "Show Message" button from? Is this even possible?

I know that I can send through the source a variable with the index i.e. iframe.html?index=0 for the first iframe.html?index=1 for the second and so on but this is not a viable solution for me because in the iframe there is going to be a lot of navigating to different pages so passing around to all the pages the index is not an option.

回答1:

Do:

var iframe_parent_div = window.frameElement ? window.frameElement.parentNode : null;


回答2:

You could write a function in the parent document that takes the iframe's name as a parameter and then get the iframe-holder div from there. Something like this should suffice:

Code in Parent Document

var findIframeHolder = function (name) {
    var $frame = $('iframe[name="' + name + '"]');
    var $frameParent = $frame.parent();
};

Code in IFrame to Call Parent Function

parent.findIframeHolder(window.name);