这是我编写的函数,用于执行此操作。我不确定它是否比jQuery模板更快。它逐个创建并附加选项元素,可能比模板慢。我怀疑模板构建整个HTML字符串,然后一次性创建DOM元素。那可能更快。对于像填充选择列表这样简单的事情,我发现此功能更易于使用,并且很好地适合我的utility.js文件中。 更新:我更新了函数,先构建HTML,然后仅调用一次append()。现在它实际上运行得更快了。感谢您发布这个问题,这使我们能够优化自己的代码。使用该函数时。
// 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;
}