javascript 国家/地区的 Select2 下拉菜单,带有标志

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18099370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:43:46  来源:igfitidea点击:

Select2 drop-down for countries, with flags

javascriptjquery-select2

提问by blueFast

Does somebody have an easy to use example of a country drop-down, with country flags, for Select2? I am about to implement one based on thissuggestion, but I would prefer to avoid reinventing the wheel.

有人有一个易于使用的国家下拉示例,带有国旗,用于Select2? 我即将根据这个建议实施一个,但我宁愿避免重新发明轮子。

回答by Starx

I was working on a similar problem and here is how I solve it.

我正在解决类似的问题,这是我解决它的方法。

(function($) {
    $(function() {
        var isoCountries = [
            { id: 'AF', text: 'Afghanistan'},
            ...
        ];
        //Assuming you have a select element with name country
        // e.g. <select name="name"></select>

        $("[name='country']").select2({
            placeholder: "Select a country",
            data: isoCountries
        });
    });
})(jQuery);

I also have made a gistabout it and following are the demos.

我也做了一个关于它的要点,下面是演示。

回答by Dementic

The way i did it:

我这样做的方式:

<div class="form-group">
    <label class="control-label">Destination</label>
    <input type="text" name="cdCountry" class="form-control" required />
</div>

<script>
    $("[name='cdCountry']").select2({
        placeholder: "Select a country",
        formatResult: function (country) {
            return $(
              "<span><i class=\"flag flag-" + country.id.toLowerCase() + "\"></i> " + country.text + "</span>"
            );;
        },
        data: yourDataSource
    });
</script>

and using the css library (css and a sprite) https://www.flag-sprites.com/

并使用 css 库(css 和 sprite) https://www.flag-sprites.com/

Official DOC

官方文件

回答by acudars

<head>
    <link href="select2.css" rel="stylesheet"/>
    <script src="select2.js"></script>
    <script>
        $(document).ready(function() { $("#e1").select2(); });
    </script>
</head>
<body>
    <select id="e1">
        <option value="1">Albania<img src="Albania.jpg"></option>
        ...
        <option value="2">Germany<img src="Germany.jpg"></option>
    </select>
</body>