2013-10-22 49 views
0

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

<!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> 
+0

与jQuery你可以尝试,并通过其确切来源$目标框架(“IFRAME [SRC =‘iframe3_get.html’]”)......你可以通过window.frames循环,并检查SRC ATTR – Joe

+0

@Joe。我认为这很容易,但我不像加快收藏等等。 – user1032531

+0

对于这个问题在循环中,您可以针对您喜欢的任何属性 – Joe

回答

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; 
     } 
    } 
}); 
+0

http://stackoverflow.com/questions/19565696/get-iframe-of-given-id描述了另一种解决方案。这可能是一个更好的解决方案。 – user1032531