简体   繁体   English

如何在select2中为所选项添加图标?

[英]How to append an icon to selected item in select2?

I'm using fontawesome, and I want to add or remove an icon to the selected item. 我正在使用fontawesome,我想添加或删除所选项目的图标。 So I did this: http://jsbin.com/nasixuro/7/edit (Thanks to @Fares M. ) 所以我这样做了: http//jsbin.com/nasixuro/7/edit (感谢@Fares M.

JS JS

$(document).ready(function () {

    function format_select2_icon(opti) {
        if (!opti.id) return opti.text; // optgroup

        if ($(opti.element).data('icon') == "1") {
            return opti.text + " <i class='fa fa-check'></i>";
        } else {
            return opti.text;
        }
    }

    $("#sel").select2({
        escapeMarkup: function(m) { return m; },
        formatResult: format_select2_icon,
        formatSelection: format_select2_icon
    });

    $("#addok").click(function() {
        actual_value = $("#sel").find(':selected').text();

        if (actual_value.indexOf(" <i class='fa fa-check'></i>") > -1){
            alert("asd");
            return;
        }

        newtext = actual_value + " <i class='fa fa-check'></i>";
        $("#sel").find(':selected').text(newtext).change();
    });

  $("#removeok").click(function() {

        actual_value= $("#sel").find(':selected').text();
        indexOk=actual_value.indexOf(" <i class='fa fa-check'></i>");

        if (indexOk > -1){
            newtext =actual_value.substring(0, indexOk);
            $("#sel").find(':selected').text(newtext).change();
            return;
        }

    });
});

HTML HTML

 <select id="sel" style="width: 100%">
    <option value="1">Hello</option>
    <option value="2" data-icon="1">Friends</option>
    <option value="3">Stackoverflow</option>
</select>
<br><br>
<button id="addok">Add <i class='fa fa-check'></i></button>
<button id="removeok">Remove <i class='fa fa-check'></i></button>

As you see, you can add or remove the icon in Hello and Stackoverflow items, but in Friends (that is the option formated with formatSelection and formatResult ), does not remove the icon, and if you try to add the icon, the appends another one to the existing. 如您所见,您可以在HelloStackoverflow项目中添加或删除图标,但在Friends (这是使用formatSelectionformatResult格式化的选项)中,不会删除图标,如果您尝试添加图标,则会附加另一个图标一个到现有的。

Do you have any idea to solve this? 你有什么想法解决这个问题吗?

I think there's two ways to achieve that: 我认为有两种方法可以实现这一目标:

  1. The first solution is the better one, 一个解决方案是更好的解决方案,

    you can make it work just by defining an escapeMarkup function in select2 options, and this function must return the same data received as input parameter without any changes. 你可以通过在select2选项中定义一个escapeMarkup函数来使它工作,并且这个函数必须返回与输入参数接收的相同数据而不做任何更改。

    all what you need is: 你需要的只是:

     $("#sel").select2({ escapeMarkup: function(m) { return m; } }); 

    here's a working example: http://jsbin.com/nasixuro/3/edit 这是一个有效的例子: http//jsbin.com/nasixuro/3/edit

  2. The second one, make a small changes in select2.js file. 第二个,在select2.js文件中进行小的更改。

    after inspecting the select2.js , i found the function which updates the text, and there was a little problem, select2.js plugin escapes html to prevent js injection, so to get it work as you expect you have to avoid escaping html and use .html() function from jquery api to insert your html instead of .append() function used in updateSelection function of select2.js . 在检查了select2.js后 ,我找到了更新文本的函数,并且有一点问题, select2.js插件转义html以防止js注入,所以要让它工作,因为你期望你必须避免转义html和使用来自jquery api的.html()函数插入你的html而不是select2.js的 updateSelection函数中使用的.append()函数。

    here's the function i'm talking about: 这是我正在谈论的功能:

     // single updateSelection: function (data) { var container=this.selection.find(".select2-chosen"), formatted, cssClass; this.selection.data("select2-data", data); container.empty(); if (data !== null) { formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup); } if (formatted !== undefined) { container.append(formatted); } cssClass=this.opts.formatSelectionCssClass(data, container); if (cssClass !== undefined) { container.addClass(cssClass); } this.selection.removeClass("select2-default"); if (this.opts.allowClear && this.getPlaceholder() !== undefined) { this.container.addClass("select2-allowclear"); } }, 

    delete this: 删除这个:

     if (data !== null) { formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup); } 

    and change: 并改变:

     if (formatted !== undefined) { container.append(formatted); } 

    to: 至:

     if (data !== undefined) { container.html(data.text); } 

    this is a dirty solution in my opinion. 在我看来,这是一个肮脏的解决方案。

    For the Remove action use this js code: 对于Remove操作,请使用以下js代码:

     $("#removeok").click(function() { actual_value= $("#sel").find(':selected').text(), indexOk =actual_value.indexOf(" <i class='fa fa-check'></i>"); if (indexOk > -1){ newtext =actual_value.substring(0, indexOk); $("#sel").find(':selected').text(newtext).change(); return; } }); 

Simply replacing < by &lt; 简单地替换< by &lt; in the option and removing format functions: 在选项和删除格式功能:

<select id="sel" style="width: 100%">
    <option value="1">Hello</option>
    <option value="2">Friends &lt;i class='fa fa-check'>&lt;/i></option>
    <option value="3">Stackoverflow</option>
</select>

You can test it here: http://jsbin.com/nasixuro/11/edit 你可以在这里测试一下: http//jsbin.com/nasixuro/11/edit

Manbe you can use the select2 parameter : formatResult or formatSelection like below Manbe你可以使用select2参数:formatResult或formatSelection,如下所示

$(document).ready(function () {

    $("#sel").select2();

    $("#addok").click(function() {
       $("#sel").select2({
          //formatResult: format
          formatSelection: format
          //escapeMarkup: function(m) { return m; }

       });
    });
});

function format(state) {
   if (!state.id) return state.text; 
   return "<i class='fa fa-check'></i>" + state.text;
}

JSBIN JSBIN

You need not do the DOM manipulation manually 您无需手动执行DOM操作

var icon_checked = "<i class='fa fa-check'></i>";

function format(opt) {
    var selection = this.element.select2("val");

    if (opt.id === selection) {
        return opt.text + icon_checked;
    }
    return opt.text;
}   

$("#sel").select2({
    formatResult: format
});

Basically this.element returns you the select element instance, on which you can run .select2("val") to get the selected value. 基本上this.element返回select元素实例,您可以在其上运行.select2("val")来获取所选值。

Compare that with the id of the object, if it is true then give the HTML with checkbox else return plain text. 将其与对象的id进行比较,如果为true则给HTML带复选框,否则返回纯文本。 I think this is what you were trying to achieve. 我认为这是你想要实现的目标。

Here is a Working fiddle , I think this is what you were trying to acheive 这是一个工作小提琴 ,我认为这是你想要实现的目标

You can`t add tags inside option. 你不能在选项中添加标签。 Try to set option font as font-family: "myfontawesome", arial; 尝试将选项字体设置为font-family:“myfontawesome”,arial; and add special character instead css replacement. 并添加特殊字符而不是css替换。

I think your problem is that you can't style values or add html to items that are in dropdown selects like you are trying to...it's pure text. 我认为你的问题是你不能设置值或将html添加到下拉选项中的项目,就像你试图...它是纯文本。

newtext = actual_value + "wat";

See how your fiddle works when I remove the html and just add plaintext : 当我删除html并添加纯文本时,看看你的小提琴是如何工作的

I also might suggest looking here . 我也建议看这里

If you want the icon to display, you need to target the HTML element and insert HTML not TEXT. 如果要显示图标,则需要定位HTML元素并插入HTML而不是TEXT。 pretty much like this: 非常像这样:

$(document).ready(function () {

    $("#sel").select2();

    $("#addok").click(function() {
        actual_value = $("#sel").find(':selected').text();

        if (actual_value.indexOf(" <i class='fa fa-check'></i>") > -1){
            alert("asd")
            return
        }

        newtext = actual_value + "<i class='fa fa-check'></i>";
        $("#s2id_sel").find('.select2-chosen').html(newtext);
    });
});

See http://jsfiddle.net/S9tE3/ http://jsfiddle.net/S9tE3/

BUT. 但。 The HTML element you need to target, from what i can see, is $(' s2id_ '+[ current element id ]). 从我所看到的,你需要定位的HTML元素是$(' s2id_ '+ [ 当前元素id ])。 s2 i guess for SELECT2 and id_. s2我猜SELECT2和id_。 So your select is id="sel", which means $('s2id_sel') . 所以你的选择是id =“sel”,这意味着$('s2id_sel') Also note that you need to find which one is chosen. 另请注意,您需要找到选择的那个。 It, conveniently enough, has a ".select2-chosen" class which makes it kinda easy to target. 它足够方便,有一个“.select2-selected”类,这使得它很容易定位。

This won't change the value, just the LOOK which is I think what you're exactly trying to do. 这不会改变价值,只是LOOK ,我认为你正在尝试做什么。

Hope that helps 希望有所帮助

Replace this code 替换此代码

  <select id="sel" style="width: 100%">
       <option value="1">Hello</option>
       <option value="2" data-icon="1">Friends</option>
       <option value="3">Stackoverflow</option>
  </select>

and put this code 并把这段代码

<select id="sel" style="width: 100%">
       <option value="1">Hello</option>
       <option value="2">Friends</option>
       <option value="3">Stackoverflow</option>
  </select>

I changed a little code to check your data-icon 我更改了一些代码来检查您的数据图标

   $("#addok").click(function() {
        actual_value = $("#sel").find(':selected').text();
       if($("#sel").find(':selected').data('icon') == '1')  
         {
           alert("asd");
           return}

Set data-icon = 0 to prevent it generate icon from format_select2_icon and remove icon. 设置data-icon = 0以防止它从format_select2_icon生成图标并删除图标。

 if($("#sel").find(':selected').data('icon') == '1')  {
          $("#sel").find(':selected').data('icon','0') ;
         $(".select2-chosen").text(actual_value).change();
        }

See: http://jsbin.com/nasixuro/18/edit 请参阅: http//jsbin.com/nasixuro/18/edit

Hope that helped for you. 希望对你有所帮助。

With fontawesome icon , you can use the following : 使用fontawesome图标 ,您可以使用以下内容:

.select2-results__option[aria-selected=true]::before {
    content: "\f0c9";
    font: normal normal normal 14px/1 FontAwesome;
    color: rbg(255,0,0);
}

There is text-equivalent of each icon : http://fortawesome.github.io/Font-Awesome/cheatsheet/ 每个图标都有相应的文字: http//fortawesome.github.io/Font-Awesome/cheatsheet/

Or if you have gif for example, it works very well simply with your image as CSS background like this : 或者,如果您有gif,例如,它可以很好地将您的图像作为CSS背景,如下所示:

.select2-results__option[aria-selected=true] {
    background: url('path/to/image.gif') no-repeat 10px 10px;
}

Here is the result : 结果如下:

下拉选择gif作为图标

With Bootstrap Glyphicons you can add the following to your CSS 使用Bootstrap Glyphicons,您可以将以下内容添加到CSS中

.select2-results__option[aria-selected=true]::after {
    font-family: "Glyphicons Halflings";
    content: "\e013";
}

and glyphicon-ok will be appended to each selected item. glyphicon-ok将附加到每个选定的项目。

Look in Bootstrap cheatsheet for icon codes. Bootstrap cheatsheet中查找图标代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM