这是我写的做到这一点的功能。我不确定它是否比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;
}
jQuery的模板是相当快的,特别是如果你是异步更新的标记。只要你只进行1次追加呼叫,而不是每个选项的值为1,那么你没事。 – Mathletics 2012-04-03 14:14:23
我们在这里谈论什么表现数字?正在添加多少个选项? – epascarello 2012-04-03 14:14:25
列表不是很大,也许是20-60个选项。在2中,我想我更关心代码量,然后是原始计算速度。 – 2012-04-03 14:17:58