列出 Select 的选项在 FF 和 IE 中给出不同的结果
在我的 JavaScript 代码中,我试图列出 Select 的选项(及其值)。这是一段代码(我正在使用 YUI2 库...日志语句只是将文本放入记录器中):
for (var opt in mySelect.options)
{
YAHOO.log('my opt, val: ' + opt + ', ' + mySelect.options[opt].value);
}
在 Firefox 中,我得到以下(正确的)输出:
my opt, val: 0, 2
my opt, val: 1, 1
my opt, val: 2, 3
my opt, val: 3, 4
my opt, val: 4, 0
但在 Internet Explorer 7 中,我得到:
my opt, val: language, undefined
my opt, val: scrollHeight, undefined
my opt, val: isTextEdit, undefined
my opt, val: currentStyle, undefined
my opt, val: document, undefined
我是至少可以说有点惊讶。我什至尝试过 (var opt in (mySelect.options)) 并且更改了变量 opt 的名称以防万一。一切都没有改变。
如果我像这样编写循环:
for (var idx=0; idx< mySelect.options.length; idx++)
{
YAHOO.log('my idx, val: ' + idx + ', ' + mySelect.options[idx].value);
}
那么 IE 也可以正常工作。
为什么第一种方法行不通?我认为 for/in 循环的工作方式与 for 循环相同。
谢谢,
保罗
In my JavaScript code I'm trying to list the options (and their values) of a Select. Here's a snippet of code (I'm using the YUI2 library...the log statement just puts text in a logger):
for (var opt in mySelect.options)
{
YAHOO.log('my opt, val: ' + opt + ', ' + mySelect.options[opt].value);
}
In Firefox I get the following (correct) output:
my opt, val: 0, 2
my opt, val: 1, 1
my opt, val: 2, 3
my opt, val: 3, 4
my opt, val: 4, 0
but in Internet Explorer 7 I get:
my opt, val: language, undefined
my opt, val: scrollHeight, undefined
my opt, val: isTextEdit, undefined
my opt, val: currentStyle, undefined
my opt, val: document, undefined
I'm a bit surprised to say the least. I even tried for (var opt in (mySelect.options)) and I changed the name of the variable opt just in case. Nothing made a difference.
If I code the loop like this:
for (var idx=0; idx< mySelect.options.length; idx++)
{
YAHOO.log('my idx, val: ' + idx + ', ' + mySelect.options[idx].value);
}
then IE works fine as well.
Why did the first way not work? I thought the for/in loop worked the same way as a for loop.
Thanks,
Paul
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
for
/in
循环遍历对象中的每个属性。您在 Firefox 中看不到这些属性,因为它们被标记为
[DontEnum]
。您应该使用普通的
for
循环来循环数组。对于普通数组,您可以通过跳过键 if
!obj.hasOwnProperty(key)
来摆脱for
/in
循环,但我'我不确定这是否适用于 DOM 对象。for
/in
loops loop over every property in an object.You aren't seeing these properties in Firefox because they're marked as
[DontEnum]
.You should use ordinary
for
loops to loop over arrays.For ordinary arrays, you can get away with a
for
/in
loop by skipping keys if!obj.hasOwnProperty(key)
, but I'm not sure whether that will work for DOM objects.