从父级获取iframe中的变量

时间:2013-10-22 20:59:17

标签: javascript dom iframe

如果我不知道父页面上有多少个iframe以及相关的iframe的顺序,如何从父级获取iframe中的变量。例如,我知道有问题的iframe是第二个,所以我可以选择windows.frames[1]。但如果我不知道它是第二个,我将如何通过ID选择它。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
        <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /> 
        <title>Testing</title>  
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js" type="text/javascript"></script>
        <style type="text/css">
        </style> 
        <script type="text/javascript"> 
            $(function(){
                $('#getValues').click(function(){
                    //This works, but I don't want to select the iframe by the number since I don't know it.
                    console.log(
                        window.frames[1],
                        window.frames[1].window,
                        window.frames[1].window.getMe
                    );
                    console.log(
                        window.frames['myIFrame'],
                        window.frames['myIFrame'].document,
                        window.frames['myIFrame'].window,
                        document.getElementById('myIFrame'),
                        document.getElementById('myIFrame').window
                    );
                });
            });
        </script>
    </head>

    <body>
        <button id="getValues">getValues</button>
        <div><iframe src="otherIframe.html"></iframe></div>
        <!-- iframe3_get.html only sets global variable getMe to something. -->
        <div><iframe id="myIFrame" src="iframe3_get.html"></iframe></div>
    </body> 
</html> 

1 个答案:

答案 0 :(得分:0)

在下面的示例中,getM1getMe2将是相同的。这似乎不是一个很好的答案,但它是我唯一的答案。如果这是一个错误的答案,你选择投票,请提供更好的答案。

$('#getValues').click(function(){
    var getMe1=window.frames[1].window.getMe;
    for (var i = window.frames.length - 1; i >= 0; i--) {
        if(window.frames[i].frameElement.id=='myIFrame'){
            var getMe2=window.frames[i].frameElement.getMe;
            break;
        }
    }
});
相关问题