【问题标题】:Backbone/Marionette with select2 v4.0, editing the tags带有 select2 v4.0 的 Backbone/Marionette,编辑标签
【发布时间】:2015-10-27 13:15:26
【问题描述】:

我有 this fiddle,它是 Backbone/Marionette 操场小提琴的扩展。我包含了 select2 js 和 css 文件。

是否可以编辑不是最后一个标签的标签?您可以在框中通过退格进行编辑,但它只允许您触摸最后一个。我希望它像一个 gmail 的“收件人”列表,您可以在其中双击一个并对其进行编辑,然后它会返回到模糊标签。

        this.$('#foo').select2({
            data: [{
                id: 1,
                text: "test1.com"
            }, {
                id: 2,
                text: "test2.com"
            }],
            multiple: true,
            allowclear: true,
            tags: [],
            placeHolder: "Click Here!",
            tokenSeparators: [',', ' '],
            minimumResultsForSearch: 1
        });

【问题讨论】:

    标签: javascript backbone.js jquery-select2


    【解决方案1】:

    不幸的是,仅使用 select2 开箱即用的功能无法做到这一点。但它的可扩展性很强,所以这就是诀窍:

    var $select2 = this.$('#foo').select2({ tags: true });
    
    var select2 = $select2.data("select2");            
    $(document.body).on("dblclick", ".select2-selection__choice", function(event) {
        var $target = $(event.target);
    
        // get the text and id of the clicked value
        var targetData = $target.data("data");
        var clickedValue = targetData.text;
        var clickedValueId = targetData.id;
    
        // remove that value from select2 selection
        var newValue = $.grep(select2.val(), function (value) {
            return value !== clickedValueId;
        });
        $select2.val(newValue).trigger("change");
    
        // set the currently entered text to equal the clicked value
        select2.$container.find(".select2-search__field").val(clickedValue).trigger("input").focus();
    });
    

    当然还有JsFiddle

    【讨论】:

    • 这是大部分的方法,但有一个致命的缺陷。如果我双击一个标签,除了第一个标签之外的所有标签都会被销毁。
    • 确实有这样的bug。我会尽快更新答案
    • @Iluvatar14 我根据您的评论更新了答案,您现在可以看一下吗?
    猜你喜欢
    • 1970-01-01
    • 2013-01-15
    • 2012-11-08
    • 1970-01-01
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    相关资源
    最近更新 更多