对于 select 下拉框赋值的问题, 网上有很多基本的这里就简单说下的了
1,
var theOption = new Option(text, value);
theElement.options[index] = theOption ;
2.
array 数组将 options 字符串 用 数组的 join() 起来,
3.
var theOption = document.createElement("option");
theOption.text = "text";
theOption.value = "value";
以上三种方式的最后基本就是来个 var selectStr = "<select ...>" + theElementString + "</select>";
这些方式对于只要初始话一次的需求是没有问题的. 关键在当前页面随时动态赋值对于已经存在的以上方式在
select 的 option 数量较少的情况(几十个). 但是在有几百个的情况下, 上面的赋值方式会让页面死在那里,其它任何操作都不能响应的了.
所以我摸索了下面第四种方式,欢迎大家批评指正
4.

/**//**
* pSelEle : origional select element node ID
* pOptStr : new options string
*/
function setSelEleOption(pSelEle, pOptStr)
...{
var parentNode = null;
var selNode = document.getElementById(pSelEle);
if(selNode)
...{
parentNode = selNode.parentNode;// Get the select element's parent node
}
var attributeStr = getSpecifiedAttr(selNode);
var newSel = '<select ' + attributeStr + ' >' + pOptStr + '</select>';
try
...{
parentNode.appendChild(document.createElement(newSel));
}catch (e)
...{
alert(" Set options for field " + pSelEle + " failed.");
}
}
function getSpecifiedAttr(pElem)
...{
if (pElem == null || (!pElem.attributes)) return "";
var attributeStr = "";
var node = null;
var nodeList = pElem.attributes;
for(var i = 0; i < nodeList.length; i++)
...{
node = nodeList.item(i);
if (!node.specified) continue;
attributeStr += node.name + "="" + node.value + "" ";
}
return attributeStr;
}

本文介绍了一种高效地为HTML中的Select元素动态更新大量选项的方法,针对数百个选项时避免页面卡顿的问题。通过创建新的Select元素并保留原有属性的方式,提高了用户体验。
1579





