これは、私はちょうどそれを行うために書いた関数です。 jQueryテンプレートよりも高速かどうかはわかりません。
Option要素を1つずつ作成して追加します。これは、テンプレート
よりも遅い場合があります。私は、TemplatesがHTML文字列全体を構築し、DOM要素を一度に作成すると考えています。それはより速いかもしれません。
私はこの機能が同じことをするために調整できると思います
。私はTemplatesを使って作業しましたが、この関数はSelectリストに値を設定するだけの簡単な方法で消費するのが簡単で、utility.jsファイルにうまく収まることがわかりました。
更新:私は最初にHTMLをビルドするように関数を更新し、append()を1回だけ呼び出します。それは実際にはるかに速く実行されます。この質問を投稿していただきありがとうございます。独自のコードを最適化できることはうれしいことです。
機能
// you can easily pass in response.d from an AJAX call if it's JSON formatted
var users = [ {id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Cindy'} ]
setSelectOptions($('#selectList'), users, 'id', 'name');
に機能コードを消費
// Fill a select list with options using an array of values as the data source
// @param {String, Object} selectElement Reference to the select list to be modified, either the selector string, or the jQuery object itself
// @param {Object} values An array of option values to use to fill the select list. May be an array of strings, or an array of hashes (associative arrays).
// @param {String} [valueKey] If values is an array of hashes, this is the hashkey to the value parameter for the option element
// @param {String} [textKey] If values is an array of hashes, this is the hashkey to the text parameter for the option element
// @param {String} [defaultValue] The default value to select in the select list
// @remark This function will remove any existing items in the select list
// @remark If the values attribute is an array, then the options will use the array values for both the text and value.
// @return {Boolean} false
function setSelectOptions(selectElement, values, valueKey, textKey, defaultValue) {
if (typeof (selectElement) == "string") {
selectElement = $(selectElement);
}
selectElement.empty();
if (typeof (values) == 'object') {
if (values.length) {
var type = typeof (values[0]);
var html = "";
if (type == 'object') {
// values is array of hashes
var optionElement = null;
$.each(values, function() {
html += '<option value="' + this[valueKey] + '">' + this[textKey] + '</option>';
});
} else {
// array of strings
$.each(values, function() {
var value = this.toString();
html += '<option value="' + value + '">' + value + '</option>';
});
}
selectElement.append(html);
}
// select the defaultValue is one was passed in
if (typeof defaultValue != 'undefined') {
selectElement.children('option[value="' + defaultValue + '"]').attr('selected', 'selected');
}
}
return false;
}
jQueryのテンプレートは、非同期的にマークアップを更新している場合は特に、かなり速いです。あなたが1つの付加的な呼び出しを行い、すべてのオプション値に対して1ではない限り、あなたは大丈夫です。 – Mathletics
私たちはここでどのようなパフォーマンスの数字を話していますか?いくつのオプションが追加されていますか? – epascarello
リストは巨大ではなく、多分20-60オプションです。 2のうち、私は、コード量と生計算速度の関係をより心配していると思います。 –