Лучший способ заполнить список выбора с помощью JQuery / Json? - PullRequest
4 голосов
/ 03 апреля 2012

В настоящее время наша команда разработчиков использует этот шаблон, но я не могу не задаться вопросом, существует ли более быстрый или более 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');
    });
}

1 Ответ

9 голосов
/ 03 апреля 2012

Это функция, которую я написал для этого. Я не уверен, что это быстрее, чем шаблоны JQuery. Создает и добавляет элементы Option по одному, что может быть медленнее, чем шаблоны . Я подозреваю, что Templates собирает всю строку 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;

}
...