1

私が書いたコードは機能しますが、もっと良くなる可能性があります。コンボ ボックスの要素ごとに 1 つずつ、同じ関数を 3 回書いています。これをより効率的にする方法に行き詰まっています。オブジェクトを作成し、各変数を配列に入れることを検討しましたが、うまく機能させることができませんでした。

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

1 に答える 1

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が、将来さらにコンボボックスが追加される場合は、このコードを再検討する価値があるかもしれません。

于 2013-09-05T21:28:12.160 に答える