【问题标题】:Best way to populate select list with JQuery / Json?用 JQuery / Json 填充选择列表的最佳方法?
【发布时间】:2012-04-17 05:03:15
【问题描述】:

目前我们的开发团队使用这种模式,但我不禁想知道是否有更快或更高效的方式来完成相同的任务。

HTML

<select id="myList" style="width: 400px;">
</select>
<script id="myListTemplate" type="text/x-jQuery-tmpl">
        <option value="${idField}">${name}</option>
</script>

这是 Javascript:

function bindList(url) {
    callAjax(url, null, false, function (json) {
        $('#myList').children().remove();
        $('#myListTemplate').tmpl(json.d).appendTo('#myList');
    });
}

【问题讨论】:

  • jQuery 模板非常快,尤其是在异步更新标记的情况下。只要您只对每个选项值进行 1 次追加调用而不是 1 次,就可以了。
  • 我们在这里谈论的性能数字是多少?增加了多少个选项?
  • 列表并不大,可能有 20-60 个选项。在这 2 个中,我想我更关心代码量而不是原始计算速度。
  • 如果您想查看一个 jQuery 插件,它可以执行此操作并具有一些附加功能,请查看 appelsiini.net/projects/chained

标签: javascript jquery json jquery-templates selectlist


【解决方案1】:

这是我为此编写的一个函数。我不确定它是否比 jQuery 模板快。 它一次创建并附加一个选项元素,这可能比模板慢。我怀疑 Templates 构建了整个 HTML 字符串,然后一口气创建了 DOM 元素。那可能会更快。 我想这个函数可以调整为做同样的事情。我使用过模板,我确实发现这个函数更容易用于填充 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} 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;

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    • 2018-11-10
    • 2015-08-24
    • 1970-01-01
    • 2019-08-27
    相关资源
    最近更新 更多