【问题标题】:Does onload function works correctly in IE10?onload 函数在 IE10 中是否正常工作?
【发布时间】:2013-10-10 15:37:38
【问题描述】:

我有一个包含多个表单的页面。我正在调用一个函数 localize(),例如<body onload = 'localize()'>

当我使用 aForms[0] = document.getElementById('form1'); 时在 localize() 函数内部 (aForms 是一个存储所有表单元素的数组)。

对于第一个表单它有效,但对于后续表单它在 IE10 中获取空值。 此页面在 IE8 和 IE9 上运行良好。

忘了说我的页面在框架内。

请帮忙。

【问题讨论】:

  • 您的表单有不同的 ID 吗?为什么不使用 document.forms,它返回文档中所有表单的数组
  • 是的,所有表单都有不同的 id。
  • 大学可能有问题但可能不是blogs.msdn.com/b/ericlippert/archive/2011/04/25/…
  • @RuneFS 嗯,是的,但在 IE 的情况下,历史上是宇宙是错误的......
  • @MattGibson 是的,但这不是这里使用的 IE 的历史版本。尽管/因为宇宙是错误的,代码更有可能在旧版本中工作

标签: javascript jquery internet-explorer internet-explorer-10


【解决方案1】:

最好将 JavaScript 与 HTML 分开。此外,您应该在 <body> 的末尾执行 JavaScript,因为您的页面会加载得更快。如果它在<head> 中,您需要加载整个脚本才能真正看到您的网站。

所以像这样设置你的 HTML:

<!doctype HTML>
<html lang="en">
    <head>
        <meta charset="utf-8"/>
        <title>Your Title</title>
    <head>
<body>
    <div></div>
    <!-- Your site here -->
    <script src="myJavaScript.js"></script>
</body>
</html>

然后在你的 JavaScript 文件中,监听 onload 事件:

window.onload = function () {
    // Use document.forms unless you need specific ones
    var forms = [
        document.getElementById('form1'),
        document.getElementById('form2')
    ];
    console.log(forms[0]);
    console.log(forms[1]); // Not null
};

请参阅:http://jsfiddle.net/C7mh2 进行演示

【讨论】:

  • 忘记在框架内提及我的页面。
  • 怎么样? jsfiddle.net/C7mh2/2 关键是这部分 iframe.contentWindow.document,它提供了对 IFrame 的文档对象的访问权限,因此您可以抓取其中的元素。
  • 我不知道为什么 document.onload 不起作用。我不得不将文档更改为窗口。
【解决方案2】:

body onload 工作正常,可能是您的代码有其他问题。 aForms[0] 是对表单的引用,而不是包含所有元素的数组。

你必须使用

aForms[0] = document.getElementById('form1')
var elements =aForms[0].getElementsByTagName('input');

// Now elements will contain all the input elements inside that aForm[0] i.e form1
  for (i=0; i<elements.length; i++){
    //some codes...
  }

您可以使用document.forms 这将返回几乎所有浏览器都支持的表单集合。这是一个例子

<body>
<form></form>
<form></form>
</body>

window.onload =function()
{
   var Forms = document.forms;
   for(var i=0;i<Forms.length;i++)
   {

       // Form[0] will contain reference to first form
       // You can use Form[i] to refer to respective form
       // If you want to check for id then following code may help you
       // Even you can check for name to by .name property

       if(Forms[0].id =='yourid')
       {
           // this is the form i want
       }
   }
}

如果您的表单包含在 iframe 中并且在同一域中

var Frames = document.getElementById( 'yourIframeId' );
var DOC = Frames.contentDocument || Frames.contentWindow.document;
var aForm = DOC.getElementById( 'form1');

【讨论】:

  • 忘了说我的页面在框架内。
  • @DeepakKumarPadhy 是否在同一个域中?
  • 是的,它在同一个域中。
猜你喜欢
  • 1970-01-01
  • 2010-09-16
  • 2017-10-12
  • 2017-05-08
  • 2016-02-05
  • 2022-01-07
  • 2016-03-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多