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

时间:2013-09-05 21:01:07

标签: c# javascript jquery sharepoint

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

    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 个答案:

答案 0 :(得分:0)

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

$(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及其兄弟姐妹放入数组中的任何显着优势,但如果在此处添加更多组合框,则可能值得重新审视此代码。将来