栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用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;}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636763.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号