1

Select2 允许<select>通过应用一些样式和功能来提高标准。我必须显示 Select2 样式的下拉列表,与 Knockout 自定义绑定。

这是一个电话号码列表,用户可以添加一些条目我希望它是可编辑的。

用户应该能够选择一个条目或键入一个可以在应用程序中使用的新条目(与 绑定manager.selectedPhoneNumber

因此,在 HTML 中:

<body>
<select id="list" data-bind="
    options: manager.getMyPhoneNumbers(),
    optionsValue: 'id',
    optionsText: 'text',
    customBinding_phoneNumbersEditableList: manager.selectedPhoneNumber
    ">
</select>
</body>

在 Javascript 中:

ko.bindingHandlers.customBinding_phoneNumbersEditableList = {
            init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
                // initialize select2 with binded element
                $(element).select2({
                    //createSearchChoice: function (term, data) {
                    //    if ($(data).filter(function () {
                    //        return this.text.localeCompare(term) === 0;
                    //    }).length === 0) {
                    //        return {
                    //            id: term,
                    //            text: term
                    //        };
                    //    }
                    //},
                    formatResult: function (item) {
                        return buildSomePrettyString();
                    },
                    formatSelection: function (item) {
                        return buildSomePrettyString();
                    },
                    sortResults: function (results, container, query) {
                        return results;
                    }
                });
            },
            update: function (element, valueAccessor, allBindings, viewModel, bindingContext) { }
        };

取消注释该功能createSearchCoice不起作用。它会导致异常Error: Option 'createSearchChoice' is not allowed for Select2 when attached to a <select> element.

有人可以帮助我吗?

4

0 回答 0