2013-02-22 53 views
2

我編寫代碼。當我試圖寫它有「IFRAME」內部單選按鈕的內容一長串象下面這樣的形式:訪問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()」函數來獲取所選單選按鈕的值?請幫助..

回答

0

長話短說。要訪問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> 
0

您將獲得的mac使用document.getElementsByName和循環在他們的陣列:

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'); 
    } 
} 

然後,您可以通過checkedItemgetIframeContent功能。

編輯

你可以分享橫跨兩頁checkedItem變量使用window

window.checkedItem = allRadios[i]; 
+0

但我認爲你在上面寫的代碼,我需要「的macinfo」 HTML文件中寫入。那麼如何在函數getIframeContent()中獲取'checkItem'變量值,我將在同一個html文件中寫入iframe正在調用'macinfo'文件? – vips 2013-02-22 14:12:24

+0

@ user1552407你可以將它存儲在window.checkedItem中,它可以在多個頁面上工作。 – 2013-02-22 14:21:45