4

我目前遇到一个问题,我的 select2 插件有时会显示上次选择的选择框的结果。另外,当我第一次单击选择框或键入速度过快时,有时我也会得到 g.results 为空。我的代码如下。

        window.currentField = ""; //current product field data
        window.currentCategory = "";   //current product category data

        //lets get some data from the hidden input for providing suggestions via ajax

        $(".suggestive-entry").live('click',function() {
            //alert("click called");
            //alert("test");

            window.currentField = $(this).siblings('input:hidden').attr('data-field'); //get the field attribute
           // alert(window.currentField);
            window.currentCategory = $(this).siblings('input:hidden').attr('data-category'); //get the category attribute
        });

        //formats select2 returned option
        function format(item) { return item.term; };

        //used for suggestive search fields
        $(".suggestive-entry").select2({
            createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.term.localeCompare(term)===0; }).length===0) { return {id:term, term:term};} },
            initSelection : function (element, callback) {
                var data = {id: element.val(), term: element.val()};
                callback(data);
            },
            multiple: false,
            ajax: {
                url: "includes/ajax/map-fields.php",
                dataType: 'json',
                data: function (term, page) {
                    //alert("suggestive called");
                    return {
                        q: term,
                        field: window.currentField,
                        ptype: window.currentCategory
                    };
                },
                results: function (data, page) {
                    return { results: data };
                }
            },

            formatSelection: format,
            formatResult: format
        });

任何帮助将不胜感激。

4

1 回答 1

1

尝试给你的隐藏字段 id,做这样的事情

   data: function (term, page) {
        //alert("suggestive called");
        var data_field = $('#someId').attr('data-field');
        var data_category = $('#someId').attr('data-category');
        return {
                q: term,
                field: data_field,
                ptype: data_category
            };
    } 
于 2013-05-20T10:01:52.887 回答