2011-06-06 24 views
0

我一直無法調試一些通常看起來很容易修復的JavaScript。我已經嘗試了幾種方法,其中一些基於使用表單來訪問字段,其他方法則使用getElementById。我也在一些地方搞亂了名稱屬性。Iframe DOM問題:訪問表單字段時出現未定義的值

在iframe文件,asdf_iframe.html:

<form id="asdf_form" name="asdf_form" action="asdf_iframe.html"> 
     <input type="hidden" id="field_1"> 
    </form> 

在基本文件:

<iframe id="asdf_iframe" name="asdf_iframe" src="asdf_iframe.html" height="50" width="50"> 
    </iframe> 

    <script> 
     function get_iframe_doc(_window,frame_id) { 
     var frame_elem = _window.document.getElementById(frame_id); 
     if(frame_elem.contentDocument) 
      return frame_elem.contentDocument; 
     else 
      return frame_elem.contentWindow.document; 
     } 
    </script> 

    <script> 
     var asdf_iframe_doc = get_iframe_doc(this,"asdf_iframe"); //Profiler says this is defined 
     asdf_iframe_doc.getElementById("field_1").value = 1234; // Error Here: not defined 
    </script> 

我試過訪問field_1許多不同的方法,但沒有成功。

+0

Hey Skolem,這兩個答案都解決了你的問題,接受一個! – 2011-06-07 22:06:12

+0

哎呀,謝謝你的擡頭。 – ThoralfSkolem 2011-06-08 20:23:25

回答

3

對我來說,看來你是太早打電話

asdf_iframe_doc.getElementById("field_1").value = 1234; 

。您需要在iframe完成加載網址後調用該方法。

這是一個嘗試。

window.onload = function() { 
    var iframe = window.frames["asdf_iframe"]; 
    iframe.onload = function() { 
     iframe.document.getElementById('field_1').value = 1234; 
    } 
} 
+0

+1。好點,還有一個很好的討論。 – Alohci 2011-06-07 00:35:39

1

您的腳本運行得太快。試試這個。

<script> 
window.onload = function() { 
    var asdf_iframe_doc = get_iframe_doc(this,"asdf_iframe"); 
    asdf_iframe_doc.getElementById("field_1").value = 1234; 
} 
</script> 
+0

它需要是iframe的onload,而不是外部頁面的onload! – 2011-06-06 23:59:40

+0

由於iframe的DOM沒有與窗口的DOM同時準備好。從概念上講,在相應的窗口觸發DOMReady事件之前,您絕不應該訪問文檔的DOM – 2011-06-07 00:03:47

+0

@Juan - 您的解決方案存在風險,即iframe上的加載事件將發生在主窗口上的加載事件之前,因此「 iframe.onload ='位會發生得太晚? – Alohci 2011-06-07 00:11:22