如何在select2下拉框中添加HTML内容 [英] How to add HTML content at select2 dropdown box

查看:645
本文介绍了如何在select2下拉框中添加HTML内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 Select2插件进行标签输入. 这是我基本工作的小提琴手.我需要在下拉框中显示每个选项/标签的已用编号",如下所示:

I've used Select2 plugin for tag input. Here is the fiddle of my basic work. I need showing "used number" of each options/tags at dropdown box like this way:

我已经在CSS(.used-number)中为该数字创建了一个类.但是,我不明白如何在HTML文件中为每个选项添加该数字.有没有办法添加这样的东西(或任何其他方式):

I've created a class for that number in my CSS (.used-number). But, I don't understand how can I add that number for each options at my HTML file. Is there a way to add those something like this(or any other way):

$(".tag").select2({
     data:[{tag: 'red',text:'3',className: 'used-number'},{tag: 'green',text:'12',className: 'used-number'},{tag: 'blue',text:'5', className: 'used-number'},{tag: 'black',text:'7'}]
});

});

推荐答案

tags数组必须包含具有键idtext的对象.您可以根据需要添加更多键(对于您的情况,我已经添加了代表数字的键qt).

The tags array must contain objects with the keys id and text. You can add more keys if you need (for your case, I've added the key qt that represents the number).

要将HTML添加到该选项,您需要更改默认的formatResult功能.使用以下代码,数字将显示在存在的标签(即,传递给select2的标签)上.对于即时创建的选项,该号码将不会显示.

To add HTML to the option you need to change the default formatResult function. With the following code, the numbers appear to the tags that exist (that is, the tags passed to the select2). For the options created on the fly, the number will not appear.

$(".tag").select2({
    tags:[
        {id: "red", text: "red", qt: 3},
        {id: "green", text: "green", qt: 12},
        {id: "blue", text: "blue", qt: 5},
        {id: "black", text: "black", qt: 7}
    ],
    formatResult: function(result) {
        if (result.qt === undefined) {
            return result.text;
        }

        return result.text
            + "<span class='used-number'>"
            + result.qt
            + "</span>";
    }
});

请参见分叉的小提琴.

这篇关于如何在select2下拉框中添加HTML内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆