开发者

Iframe DOM Problem: undefined values when accessing form field

开发者 https://www.devze.com 2023-03-11 08:02 出处:网络
I\'ve been having trouble debugging some JavaScript which normally would seem easy to fix.I\'ve tried several methods, some based on using a form to access fields, other ways by using getElementById.I

I've been having trouble debugging some JavaScript which normally would seem easy to fix. I've tried several methods, some based on using a form to access fields, other ways by using getElementById. I've also messed around with leaving in/out the name attributes in several places.

In the Iframe File, asdf_iframe.html:

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

In the base file:

    <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>

I've tried many different methods of accessing field_1, but with no success.


To me, it seems you are calling

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

Too early. You need to call that method after the iframe finished loading its url.

Here's an attempt.

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


Your script is simply running too soon. Try this instead.

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

精彩评论

暂无评论...
验证码 换一张
取 消