Javascript函数在FF,Opera等中运行,在IE8中失败 - 如何修复 [英] Javascript function works in FF, Opera etc, fails in IE8 - how to fix

查看:93
本文介绍了Javascript函数在FF,Opera等中运行,在IE8中失败 - 如何修复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下功能(在IE6中工作但在IE8中被破坏)

I have the following function (worked in IE6 but is broken in IE8)

function implode() { var str = '';
    for(item in globvars)  //<- IE8 wets itself here ...
       str+= '\n' + globvars[item]+';';
    return str+'\n';
}

这似乎是一个无害的小功能,但是IE8非常适合它。任何人都可以告诉我如何重写它,以便在IE8(以及其他浏览器)中工作吗?

It seems an innocuous little function, but IE8 dosent grok it. Can anyone show me how to rewrite this so it work in IE8 (as well as the other browsers)?

在脚本开头(即标签后面的第一行,我已经定义了像这样的globvars:

At the begining of the script (i.e. first line after the tag, I have defined the globvars like this:

var globvars = new Array();  // This should give globvars global scope

来自IE8的错误是:

对象不支持此操作

推荐答案


我的脚本中没有其他地方的变量命名项目

I DO NOT have a variable named item anywhere else in my script

你将但是,有一个元素 id =item name =item .IE镜像元素id / name不仅仅是 document.item 而且 window.item 。(显然依赖于这两种情况都是不好的做法。)

You will, however, have an element with id="item" or name="item". IE mirrors elements with an id/name not just as document.item but also window.item. (Obviously it's bad practice to rely on either.)

所以当你说 item = 而不告诉它你想要 var ,傻傻的IE瘦你试图分配给现有的HTMLElement,其id / name位于窗口中,并因为元素不可写而抛出拟合。即使对于全局变量,这也是始终使用 var 的一个原因。

So when you say item= without telling it you want a var, silly IE thinks you're trying to assign to the existing HTMLElement with that id/name sitting in the window, and throws a fit because elements aren't writable. This is one reason to always use var even for global variables.

您不应该使用 for ... in 迭代一个数组。它不符合你的想法。它可能以错误的顺序返回数组项,并可能返回意外的非数字属性。始终使用普通的旧获取(var i = 0; i< array.length; i ++)循环来获取数组中的项目; for ... in 仅用于 Object 用作映射。

You shouldn't use for...in to iterate an Array. It doesn't do what you think. It may return the array items in the wrong order, and potentially unexpected non-numeric properties. Always use the plain old for (var i= 0; i<array.length; i++) loop for getting the items in an Array; for...in is only for Object used as a mapping.

无论如何,JavaScript的内置 join()几乎可以为你工作:

Anyhow, JavaScript's built-in join() almost does the work for you:

function implode() {
    return '\n'+globvars.join(';\n')+';\n';
}

这篇关于Javascript函数在FF,Opera等中运行,在IE8中失败 - 如何修复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆