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

4

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

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模板非常快速,特别是在异步更新标记时。只要您只进行一次追加调用而不是每个选项值都进行一次,那么一切都很好。 - Evan Davis
我们在谈论什么性能数字?有多少选项正在添加? - epascarello
这些列表不是很大,可能只有20-60个选项。在这两者之间,我更关心的是代码量而不是原始计算速度。 - Tom Halladay
如果您想要查看一个具有此功能并且具有一些附加功能的jQuery插件,请访问http://www.appelsiini.net/projects/chained。 - Matt Browne
1个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
9
这是我编写的函数,用于执行此操作。我不确定它是否比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;

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,