Firefox使用表单元素值检索iframe的内容

时间:2009-08-09 05:13:39

标签: javascript firefox

我有iframe与表单元素,如输入,选择textarea等。我需要获得整个iframe内容与输入的值到这些元素。在IE 7,8中它可以正常工作,但在FF中我会变为空值或默认值。

以下是代码段:

iframe内容

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <title>Untitled Document</title>
  </head>
  <body>
    <div id="content">
      <input name="fn" type="text" id="fn"/>
      <select name="states">
        <option val=""></option>
        <option val="ca">CA</option>
        <option val="co">CO</option>
        <option val="ce">CE</option>
        <option val="cI">CI</option>
      </select>
    </div>
  </body>
</html>

父页面内的Javascript

  function getContentFromIframe(iFrameName){  
      var myIFrame = document.getElementById(iFrameName);
      var content = myIFrame.contentWindow.document.body.innerHTML;
  }
  //calling function for example on button click
  alert(getContentFromIframe('frame1'));

我在输入中输入了值,并在上面的select和ran脚本中选择了一些内容。在IE中我得到输入值的内容,但是ff和其他浏览器只返回加载时的html,尽管我可以单独检索值,例如使用jquery

  $('#frame1').contents().find('#fn').val()

我真的堆积了这个问题。请帮我。 感谢。

可能有没有其他方法可以在不使用innerHTML的情况下获取此内容?

3 个答案:

答案 0 :(得分:1)

这与在框架中无关 - innerHTML在不同的浏览器上表现不同。即使是简单的案例

<div id=mydiv><input name=in id=inval value=100></div>

将表现出相同的行为。我没有看到单独检索值的替代方法。

答案 1 :(得分:0)

如果使用jquery,则可以使用serialize()方法检索所有输入的名称/值对。只需将输入字段包装到表单元素中,而不是像这样将它们包装起来:

var input_vals=$("iframe").contents().find("form").serialize();

//output:
//"fn=bla&states=CO"

答案 2 :(得分:0)

实际上解决方案已发布在StackOverflow上,但我错过了原版。 可能是其他人需要此功能我在这里使用我的小更新重新发布代码

这个jquery插件只是在我们获取innerHtml之前更新字段

(function($) {
    var oldHTML = $.fn.html;

    $.fn.formhtml = function() {
        if (arguments.length) return oldHTML.apply(this, arguments);
        $("input,textarea,button", this).each(function() {
            this.setAttribute('value', this.value);
        });

        $("select option", this).each(function() {
            if (this.selected)
                this.setAttribute('selected', 'selected');
            else
                this.removeAttribute('selected');
        });

        $("textarea", this).each(function() {
            $(this).html(this.value);
        });

        $(":radio,:checkbox", this).each(function() {
            // im not really even sure you need to do this for "checked"
            // but what the heck, better safe than sorry
            if (this.checked) this.setAttribute('checked', 'checked');
            else this.removeAttribute('checked');
        });
        return oldHTML.apply(this);
    };

    //optional to override real .html() if you want
    // $.fn.html = $.fn.formhtml;
})(jQuery);