动态创建选择元素并从sharepoint列表中填充选项

我写的代码有效,但可能更好。 我写了三次相同的函数,每个combobox元素一个。 我坚持如何提高效率。 我已经看过创建一个对象并将每个变量放在一个数组中,但我无法成功地使它工作。

var csCategory = , csKeyword = , csEntity = ; addOption = function (selectbox, text, value) { var optn = document.createElement("OPTION"); optn.text = text; optn.value = value; selectbox.options.add(optn); } $(function () { // Temp test stuff to populate option list var selectObj = document.getElementById("combobox1") if (selectObj) { for (var i=0; i < csCategory.length;++i){ addOption(selectObj, csCategory[i], csCategory[i]); } } }); $(function () { // Temp test stuff to populate option list var selectObj = document.getElementById("combobox2") if (selectObj) { for (var i=0; i < csKeyword.length;++i){ addOption(selectObj, csKeyword[i], csKeyword[i]); } } }); $(function () { // Temp test stuff to populate option list var selectObj = document.getElementById("combobox3") if (selectObj) { for (var i=0; i < csEntity.length;++i){ addOption(selectObj, csEntity[i], csEntity[i]); } } }); 

显而易见的第一步是重构共享代码。 所以:

 $(function () { // Temp test stuff to populate option list var selectObj = document.getElementById("combobox2") if (selectObj) { for (var i=0; i < csKeyword.length;++i){ addOption(selectObj, csKeyword[i], csKeyword[i]); } } }); ( ... etc ... ) 

变为:

 function populate(id, collection) { var selectObj = document.getElementById(id) if (selectObj) { for (var i=0; i < collection.length;++i){ addOption(selectObj, collection[i], collection[i]); } } } $(function () { populate ("combobox1", csCategory); populate ("combobox2", csKeyword); populate ("combobox3", csEntity); }); 

combobox1及其兄弟姐妹放入arrays的这个阶段 ,我看不出任何明显的优势,但如果将来添加更多的combobox,可能值得重新考虑这个代码。