我在 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/