问题
The code I wrote works, but it could be better. I am writing out the same function three times, one for each of the combo box elements. I am stuck on how to make this more efficient. I have looked at creating an object and putting each of the variables in an array, but I was not able to successfully get it working.
var csCategory = <%=csCategoryArray%>,
csKeyword = <%=csKeywordArray%>,
csEntity = <%=csEntityArray%>;
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]);
}
}
});
回答1:
The obvious first step is to refactor out the shared code. So:
$(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 ... )
becomes:
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);
});
I can't see any significant advantage at this stage of putting combobox1
and its siblings into an array, but it may be worthwhile revisiting this code if more comboboxes are added in the future.
来源:https://stackoverflow.com/questions/18645896/dynamically-creating-select-elements-and-populating-options-from-sharepoint-list