---
title: "简单地封装chosen支持option动态生成"
author: "bee1314"
date: "2014-06-10T14:09:36Z"
tags: []
categories: ["Web前端"]
slug: "chosen-option"
draft: false
lastmod: "2014-06-10T14:09:36Z"
id: 2077906
url: "https://bee1314.iteye.com/blog/2077906"
---

为了美化select的显示效果，决定使用chosen来渲染体验。

 

因为页面中的select的option都是通过handlerbars动态的生成，所以导致options动态的改变时，chosen不能实时的刷新，停留在上一刻，影响用户体验。查询官方的api，只有通过$('#test').chosen('destroy').chosen();销毁一次再重建一次才可以正常的显示，但是如果这样写，导致页面到处是这样的垃圾代码-丑且脏， 因为有时还要判断出什么时候使用$('#test').chosen({})。于是写一个jquery的插件，来简单地封装下chosen地api，支持我们的场景。

```

```

```
/**
     * 到处是chosen和chosen('destroy').chosen?
     * 我们要思考root casuse？
     *   根本原因是因为使用handlerbars动态生成的select的内容
     *   导致chosen无法同步刷新，那我们为何不自己扩展呢？
     */
    (function($) {
        /**
         * 创建动态的chosen插件
         * --智能判断chosen有没有加载
         * @param param
         *    param为destroy就为销毁该chosen
         *    param为“”， 表示option不是动态的生成的，页面已经渲染了options
         *    其他的都是为动态生成的options html片段
         */
        $.fn.dynamicChosen = function(param) {
            //简单地设置chosen属性
            var opt = {
                disable_search_threshold: 10,
                no_results_text: ':)，暂无匹配'
            };
            return this.each(function() {
                //得到当前的元素id，chosen的id会在元素的id基础上添加_chosen
                var id = $(this).prop('id');
                var $chosenId = $('#' + id + '_chosen');

                if (param == 'destroy') {
                    //如果没有渲染chosen，说明就是普通的select直接隐藏
                    if ($chosenId.length == 0) {
                        $(this).hide();
                    } else {
                        $(this).chosen('destroy').hide();
                    }
                } else {
                    //如果chosen没有在页面渲染
                    if ($chosenId.length == 0) {
                        //trim(param)说明option非动态生成
                        if ($.trim(param)) {
                            $(this).html(param).show().chosen(opt);
                        } else {
                            $(this).show().chosen(opt);
                        }

                    } else {
                        if ($.trim(param)) {
                            $(this).html(param).show().chosen('destroy').chosen(opt);
                        } else {
                            $(this).html(param).show().chosen('destroy').chosen(opt);
                        }
                    }
                }
            });
        }
    })(jQuery);
```

```
 
```

 

```
使用：
//销毁
$("#test").dynamicChosen('destroy')

//渲染已经存在的select和option
$("#test").dynamicChosen();

//动态的渲染
var tpl = function (templateId, data) {
        var template = Handlebars.compile($(templateId).html());
        return template(data);
    };

$("#test").dynamicChosen(tpl('#test-tpl', {list: {..}}));
```