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

dynamically creating select elements and populating options from sharepoint list

本文关键字:SharePoint 列表 填充 选项 创建 选择 元素 动态      更新时间:2023-09-26

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

    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]);
        }
    }
});

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

$(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及其同级放入数组的任何显着优势,但如果将来添加更多组合框,则可能值得重新访问此代码。