【问题标题】:accessing selected radio button value inside iframe [duplicate]访问 iframe 中选定的单选按钮值 [重复]
【发布时间】:2013-02-08 03:22:44
【问题描述】:

我编写代码。我正在尝试编写一个在“iframe”中包含一长串单选按钮内容的表单,如下所示:

<form name="iframeform" method="POST" action="http://localhost/cgi-bin/run">
    <tr>
            <td><iframe id="macList" src="http://localhost/macinfo" style="width:1000px;height:160px">
            </iframe></td>
    </tr>
    <tr>
            <input type="hidden" name="macaddr" value="">
            <td><input type="submit" name="macselect" value="Continue" id="stdbtn" onclick="getIframeContent()"></td>
    </tr>
</form>

'iframe' 指向 macinfo 页面的代码如下:

<html>
<body>
<table>
<tr>
<td><input type=radio name=mac value=E8:B7:48:7B:C0:4A>abc.example.com</td>
</tr>
<tr>
<td><input type=radio name=mac value=00:17:08:5A:81:CF>xyz.cisco.com</td>
</tr>
....
</table>
</body>
</html>

如何编写“getIframeContent()”函数来获取选定单选按钮的值?请帮忙..

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    长话短说。要访问 iframe document 使用 .contentWindow.document,即:

    document.getElementById('macList').contentWindow.document
    

    还有一个示例代码:

    <html>
      <head>
        <script type="text/javascript">
          function getIframeContent(){
             var myIFrame = document.getElementById('macList');
             var myIFDoc  = myIFrame.contentWindow.document;
             var myRadios = myIFDoc.getElementsByName("mac");
    
             var checkedItemValue = "";
             for(var i=0; i<myRadios.length; i++) {
                if (myRadios[i].checked) {
                   checkedItemValue = myRadios[i].value;
                }
             }
             if (checkedItemValue) {
                alert(checkedItemValue);
             } else {alert('Select address');}
          }
        </script>
      </head>
    <body>
    
      <iframe id="macList" src="..." 
          style="width:600px;height:160px">
      </iframe>
    
      <input type="submit" onclick="getIframeContent();">
    
    </body>
    </html>
    

    【讨论】:

      【解决方案2】:

      您必须使用document.getElementsByName 获取mac 的数组并遍历它们:

      var allRadios = document.getElementsByName("mac");
      var checkedItem; 
      for(var i=0; i<allRadios.length; i++) {
           if (allRadios[i].checked) {
                checkedItem = allRadios[i];
                alert('Found checked radio button');
           }
       }
      

      然后您可以将checkedItem 传递给您的getIframeContent 函数。

      编辑

      您可以使用window 在两个页面之间共享checkedItem 变量

      window.checkedItem = allRadios[i];
      

      【讨论】:

      • 但是我认为你上面写的代码,我需要写在'macinfo' html文件中。那么如何在函数getIframeContent()中获取'checkItem'变量值,我将把它写在同一个html文件中,其中iframe正在调用'macinfo'文件?
      • @user1552407 你可以将它存储在 window.checkedItem 中,它可以跨多个页面工作。
      猜你喜欢
      • 2017-01-30
      • 2020-02-16
      • 2019-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-13
      • 2018-10-11
      • 2016-06-02
      相关资源
      最近更新 更多