Select2 按需加载本地/离线数据

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8" />
        <title></title>
        <link href="https://cdn.bootcss.com/select2/3.5.3/select2.min.css" rel="stylesheet">
    </head>

    <body>
        <!--<select id="test" class="form-control" style="width: 220px;"> </select>-->
        
        <input type="hidden" id="e5" style="width:300px"/>

        <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
        <!--<script src="https://cdn.bootcss.com/select2/4.0.3/js/select2.min.js"></script>-->
        
            <script src="https://cdn.bootcss.com/select2/3.5.3/select2.min.js"></script>
        <script>
            $(document).ready(function() {
                var a = [{
                        "id": 1,
                        "text": "9405"
                    },
                    {
                        "id": 2,
                        "text": "9404"
                    },
                    {
                        "id": 3,
                        "text": "9403"
                    },
                    {
                        "id": 1,
                        "text": "940501"
                    },
                    {
                        "id": 1,
                        "text": "9407"
                    },
                    {
                        "id": 1,
                        "text": "9408"
                    },
                    {
                        "id": 1,
                        "text": "9409"
                    },
                    {
                        "id": 1,
                        "text": "8501"
                    }
                ];
                

                $("#e5").select2({
                    minimumInputLength: 1,
                    query: function(query) {
                    debugger;
                        var data = {results: []};
                        for(var o in a) {
                            var p = a[o].text;
                            if(p.indexOf(query.term) >= 0) {
                                data.results.push({id: a[o].id, text:a[o].text});
                            };
                        }
                        console.log(data);
                        query.callback(data);
                    }
                });
            });
        </script>
    </body>

</html>

 

posted @ 2017-05-11 15:21  游子善心  阅读(10)  评论(0)    收藏  举报  来源