javascript - 动态创建的 Select 元素在 FF 和 Chrome 中是不同的

标签 javascript google-chrome

我在 JavaScript 中创建 Select 元素时有些奇怪:

var items = {"3":"Three","1":"One","2":"Two"};
var elem = document.createElement("select");

for ( var key in items) {
    var ov = document.createElement("option");
    ov.value = key; 
    ov.appendChild(document.createTextNode(items[key]))
    elem.appendChild(ov);
}

document.getElementById('someDiv').appendChild(elem);

FF 创建具有初始元素顺序(三、一、二)的 Select 元素。 Chrome 按键对元素进行排序,并以下一方式(一、二、三)输出。

为什么会这样?以及如何防止在 Chrome 中排序?

最佳答案

for … in 语句以不可预知的顺序遍历对象。作为 MDC says :

A for...in loop iterates over the properties of an object in an arbitrary order (see the delete operator for more on why one cannot depend on the seeming orderliness of iteration, at least in a cross-browser setting).

你最好使用对象数组并使用普通的for循环来保持指定的顺序,比如:

var items = [{"3":"Three"}, {"1":"One"}, {"2":"Two"}];

for (var i = 0; i < items.length; i++}
    /* etc */ ;

附带说明:当使用for … in 遍历对象时,您确实应该使用hasOwnProperty。检查它是否是继承的属性,否则您可能会在 select 框中包含继承的属性。

关于javascript - 动态创建的 Select 元素在 FF 和 Chrome 中是不同的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4758557/

相关文章:

javascript - rowRange.setBackgroundColor 已弃用

javascript - 在不使用用户代理的情况下在 javascript 中检测 iPad?

google-chrome - 运行 jekyll serve (ECONNRESET) 时,Chrome 中无法播放嵌入式本地 mp4

javascript - 打印对象时 JavaScript Google Chrome 控制台中的错误

api - 是否可以通过 chrome webstore api 上传/发布未列出的扩展程序?

javascript - 包含无填充或间距的 JQM 小部件的 HTML 表

javascript - 将 knockout 与关联数组一起使用

javascript - 尽管使用了 jQuery,datepicker 仍然无法工作

javascript - Chrome 扩展程序 : How to open a specified link in a new tab by clicking a button in the html popup?

python - 如何使用当前用户数据远程创建 Python Selenium Chrome webdriver?