Internet Explorer中的对象预期错误

Ste*_*ard 6 javascript

该代码可以在Firefox和Chrome中正常运行。

在Internet Explorer中加载页面时,您会收到错误消息

用户代理:Mozilla / 4.0(兼容; MSIE 8.0; Windows NT 6.1; WOW64; Trident / 4.0; GTB6.5; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729;媒体Center PC 6.0; eSobiSubscriber 2.0.4.16; FDM; InfoPath.3)时间戳:2010年8月18日星期三13:48:54 UTC

当您按下链接时

<a href="javascript:toggleLayer('sub< ? echo $l; ?>');"><? echo $alp[$l]; ?></a> 
Run Code Online (Sandbox Code Playgroud)

你得到错误

消息:对象预期
行:4
字符:1
代码:0
URI:

消息:必需的对象
行:24
字符:4
代码:0
URI:

在Firefox或Chrome中没有错误,只有IE。

任何帮助,将不胜感激。这是我的代码:

function toggleLayer( whichLayer )
{
  var sub=new Array();
  for (i=1;i<25;i++)
  {
  sub[i] = 'sub'+i;
 }
  var elem, vis;
  if( document.getElementById ) // this is the way the standards work
    elem = document.getElementById( whichLayer );
  else if( document.all ) // this is the way old msie versions work
      elem = document.all[whichLayer];
  else if( document.layers ) // this is the way nn4 works
    elem = document.layers[whichLayer];
  vis = elem.style;
  // if the style.display value is blank we try to figure it out here



  for (i=1;i<26;i++)
 {
   eelem = document.getElementById( sub[i] );
   vvis = eelem.style;
   if(eelem==elem){
    vvis.display = "block";
    } else {
    vvis.display = "none";
    }
 }

  if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}
Run Code Online (Sandbox Code Playgroud)

HoL*_*ieR 5

问题

Internet Explorer 中的“预期对象”/“需要对象”错误消息相当模糊,但通常在您尝试访问未定义元素的属性时触发。

在您的情况下,您可能尝试访问的未定义元素很可能位于此处:

for (i=1;i<26;i++)
 {
   eelem = document.getElementById( sub[i] ); // <---- UNDEFINED
   vvis = eelem.style; // <----- ERROR
   if(eelem==elem){
    vvis.display = "block";
    } else {
    vvis.display = "none";
    }
 }
Run Code Online (Sandbox Code Playgroud)

元素“eelem”在数组的最后一次迭代中未定义,因为您之前仅使用索引1 到 24初始化了数组“sub” 。在最后一次迭代中,您试图访问索引25。所以在最后一次迭代中会发生什么:

eelem = document.getElementById( sub[i] );
Run Code Online (Sandbox Code Playgroud)

是相同的

eelem = document.getElementById( undefined );
Run Code Online (Sandbox Code Playgroud)

哪个返回 undefined 给 elelem。当您访问变量 eelem 的属性时会触发该错误,因为 undefined 没有属性。

解决方案

为了防止这种情况发生,您应该使用索引 1 到 25 初始化数组,或者在第二个循环中,只循环元素 1 到 24。