用JQueryJson填充选择列表的最佳方法?

用JQueryJson填充选择列表的最佳方法?,第1张

用JQuery / Json填充选择列表的最佳方法?

这是我为此编写的函数。我不确定它是否比jQuery Templates更快。 它一次创建并附加一个Option元素,这可能比Templates慢
。我怀疑Templates会构建整个HTML字符串,然后一次创建所有DOM元素。那可能更快。 我想可以将此功能调整为执行相同的 *** 作
。我已经使用了Templates,但确实发现此功能更易于使用,就像填充Select列表一样简单,它非常适合我的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} falsefunction 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;}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5642596.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存