The current repo belongs to Paused status, and some functions are restricted. For details, please refer to the description of repo status
Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
selectpage.min.js 33.49 KB
Copy Edit Raw Blame History
TerryZ authored 2017-06-13 15:43 . 初始上传
;(function($){"use strict";var constants={dataKey:'selectPageObject',objStatusKey:'selectPage-self-mark',objStatusIndex:'selectPage-self-index'};$.fn.selectPage=function(source,option){var arr=[];this.each(function(){arr.push(new SelectPage(this,source,option));});return(option!==undefined&&option.instance!==undefined&&option.instance)?$(arr):this;};function SelectPage(combo_input,source,option){this._setOption(source,option);this._setLanguage();this._setCssClass();this._setProp();this._setElem(combo_input,option);this._setButtonAttrDefault();this._setInitRecord();this._ehButton();this._ehComboInput();this._ehWhole();$(this.elem.container).data(constants.dataKey,this);}$.extend(SelectPage.prototype,{_setOption:function(source,option){option=this._setOption1st(source,option);option=this._setOption2nd(option);this.option=option;},_setOption1st:function(source,option){return $.extend({source:source,lang:'cn',multiple:false,init_record:false,db_table:'tbl',field:'name',and_or:'AND',per_page:10,primary_key:'id',button_img:'dist/btn.png',bind_to:false,focus_drop_list:true,auto_select_first:false,auto_fill_result:false,no_result_clean:false,format_item:false,select_only:false,},option);},_setOption2nd:function(option){option.search_field=(option.search_field===undefined)?option.field:option.search_field;option.and_or=option.and_or.toUpperCase();var arr=['hide_field','show_field','search_field'];for(var i=0;i<arr.length;i++){option[arr[i]]=this._strToArray(option[arr[i]]);}option.order_by=(option.order_by===undefined)?option.search_field:option.order_by;option.order_by=this._setOrderbyOption(option.order_by,option.field);return option;},_strToArray:function(str){if(!str)return'';return str.replace(/[\s ]+/g,'').split(',');},_setOrderbyOption:function(arg_order,arg_field){var arr=[],orders=[];if(typeof arg_order=='object'){for(var i=0;i<arg_order.length;i++){orders=$.trim(arg_order[i]).split(' ');arr[i]=(orders.length==2)?orders:[orders[0],'ASC'];}}else{orders=$.trim(arg_order).split(' ');arr[0]=(orders.length==2)?orders:(orders[0].match(/^(ASC|DESC)$/i))?[arg_field,orders[0]]:[orders[0],'ASC'];}return arr;},_setLanguage:function(){var message;switch(this.option.lang){case'de':message={add_btn:'Hinzufügen-Button',add_title:'Box hinzufügen',del_btn:'Löschen-Button',del_title:'Box löschen',next:'Nächsten',next_title:'Nächsten'+this.option.per_page+' (Pfeil-rechts)',prev:'Vorherigen',prev_title:'Vorherigen'+this.option.per_page+' (Pfeil-links)',first_title:'Ersten (Umschalt + Pfeil-links)',last_title:'Letzten (Umschalt + Pfeil-rechts)',get_all_btn:'alle (Pfeil-runter)',get_all_alt:'(Button)',close_btn:'Schließen (Tab)',close_alt:'(Button)',loading:'lade...',loading_alt:'(lade)',page_info:'num_page_top - num_page_end von cnt_whole',select_ng:'Achtung: Bitte wählen Sie aus der Liste aus.',select_ok:'OK : Richtig ausgewählt.',not_found:'nicht gefunden',ajax_error:'Bei der Verbindung zum Server ist ein Fehler aufgetreten. (ajax-combobox)'};break;case'en':message={add_btn:'Add button',add_title:'add a box',del_btn:'Del button',del_title:'delete a box',next:'Next',next_title:'Next'+this.option.per_page+' (Right key)',prev:'Prev',prev_title:'Prev'+this.option.per_page+' (Left key)',first_title:'First (Shift + Left key)',last_title:'Last (Shift + Right key)',get_all_btn:'Get All (Down key)',get_all_alt:'(button)',close_btn:'Close (Tab key)',close_alt:'(button)',loading:'loading...',loading_alt:'(loading)',page_info:'num_page_top - num_page_end of cnt_whole',select_ng:'Attention : Please choose from among the list.',select_ok:'OK : Correctly selected.',not_found:'not found',ajax_error:'An error occurred while connecting to server. (ajax-combobox)'};break;case'cn':message={add_btn:'添加按钮',add_title:'添加区域',del_btn:'删除按钮',del_title:'删除区域',next:'下一页',next_title:''+this.option.per_page+' (→)',prev:'上一页',prev_title:''+this.option.per_page+' (←)',first_title:'首页 (Shift + ←)',last_title:'尾页 (Shift + →)',get_all_btn:'获得全部 (↓)',get_all_alt:'(按钮)',close_btn:'关闭 (Tab键)',close_alt:'(按钮)',loading:'读取中...',loading_alt:'(读取中)',page_info:'num_page_top - num_page_end (共 cnt_whole)',select_ng:'请注意:请从列表中选择.',select_ok:'OK : 已经选择.',not_found:'无查询结果',ajax_error:'连接到服务器时发生错误!'};break;case'es':message={add_btn:'Agregar boton',add_title:'Agregar una opcion',del_btn:'Borrar boton',del_title:'Borrar una opcion',next:'Siguiente',next_title:'Proximas '+this.option.per_page+' (tecla derecha)',prev:'Anterior',prev_title:'Anteriores '+this.option.per_page+' (tecla izquierda)',first_title:'Primera (Shift + Left)',last_title:'Ultima (Shift + Right)',get_all_btn:'Ver todos (tecla abajo)',get_all_alt:'(boton)',close_btn:'Cerrar (tecla TAB)',close_alt:'(boton)',loading:'Cargando...',loading_alt:'(Cargando)',page_info:'num_page_top - num_page_end de cnt_whole',select_ng:'Atencion: Elija una opcion de la lista.',select_ok:'OK: Correctamente seleccionado.',not_found:'no encuentre',ajax_error:'Un error ocurrió mientras conectando al servidor. (ajax-combobox)'};break;case'pt-br':message={add_btn:'Adicionar botão',add_title:'Adicionar uma caixa',del_btn:'Apagar botão',del_title:'Apagar uma caixa',next:'Próxima',next_title:'Próxima '+this.option.per_page+' (tecla direita)',prev:'Anterior',prev_title:'Anterior '+this.option.per_page+' (tecla esquerda)',first_title:'Primeira (Shift + Left)',last_title:'Última (Shift + Right)',get_all_btn:'Ver todos (Seta para baixo)',get_all_alt:'(botão)',close_btn:'Fechar (tecla TAB)',close_alt:'(botão)',loading:'Carregando...',loading_alt:'(Carregando)',page_info:'num_page_top - num_page_end de cnt_whole',select_ng:'Atenção: Escolha uma opção da lista.',select_ok:'OK: Selecionado Corretamente.',not_found:'não encontrado',ajax_error:'Um erro aconteceu enquanto conectando a servidor. (ajax-combobox)'};break;case'ja':message={add_btn:'追加ボタン',add_title:'入力ボックスを追加します',del_btn:'削除ボタン',del_title:'入力ボックスを削除します',next:'次へ',next_title:'次の'+this.option.per_page+'件 (右キー)',prev:'前へ',prev_title:'前の'+this.option.per_page+'件 (左キー)',first_title:'最初のページへ (Shift + 左キー)',last_title:'最後のページへ (Shift + 右キー)',get_all_btn:'全件取得 (下キー)',get_all_alt:'画像:ボタン',close_btn:'閉じる (Tabキー)',close_alt:'画像:ボタン',loading:'読み込み中...',loading_alt:'画像:読み込み中...',page_info:'num_page_top - num_page_end 件 (全 cnt_whole 件)',select_ng:'注意 : リストの中から選択してください',select_ok:'OK : 正しく選択されました。',not_found:'(0 件)',ajax_error:'サーバとの通信でエラーが発生しました。(ajax-combobox)'};break;}this.message=message;},_setCssClass:function(){var css_class={container:'sp_container',container_open:'sp_container_open',selected:'sp_selected',re_area:'sp_result_area',element_box:'sp_element_box',navi:'sp_navi',results:'sp_results',re_off:'sp_results_off',select:'sp_over',select_ok:'sp_select_ok',select_ng:'sp_select_ng',input_off:'sp_input_off',button:'sp_button',btn_on:'sp_btn_on',btn_out:'sp_btn_out',input:'sp_input'};this.css_class=css_class;},_setProp:function(){this.prop={is_suggest:false,page_all:1,page_suggest:1,max_all:1,max_suggest:1,is_paging:false,is_loading:false,xhr:false,key_paging:false,key_select:false,prev_value:''};this.template={tag:{content:'<li class="selected_tag" itemvalue="#item_value#">#item_text#<span class="tag_close">x</span></li>',textKey:'#item_text#',valueKey:'#item_value#'}};},_setElem:function(combo_input,option){var elem={};elem.combo_input=$(combo_input).attr({'autocomplete':'off'}).addClass(this.css_class.input).wrap('<div>');elem.container=$(elem.combo_input).parent().addClass(this.css_class.container);if($(combo_input).hasClass('input-block-level'))$(elem.container).css('width','100%');else $(elem.container).width($(combo_input).outerWidth());elem.button=$('<div>').addClass(this.css_class.button);elem.img=$('<span class="bs-caret"><span class="caret"></span></span>');elem.element_box=$('<ul>').addClass(this.css_class.element_box);elem.result_area=$('<div>').addClass(this.css_class.re_area);elem.navi=$('<div>').addClass('pagination').append('<ul>');elem.results=$('<ul>').addClass(this.css_class.results);var namePrefix='_text';var input_id=($(elem.combo_input).attr('id')!==undefined)?$(elem.combo_input).attr('id'):$(elem.combo_input).attr('name');var input_name=($(elem.combo_input).attr('name')!==undefined)?$(elem.combo_input).attr('name'):'selectPage';var hidden_name=input_name,hidden_id=input_id;if(input_name.match(/\]$/))input_name=input_name.replace(/\]?$/,namePrefix);else input_name+=namePrefix;if(input_id.match(/\]$/))input_id=input_id.replace(/\]?$/,namePrefix);else input_id+=namePrefix;elem.hidden=$('<input type="hidden" class="sp_hidden" />').attr({name:hidden_name,id:hidden_id}).val('');$(elem.combo_input).attr({name:input_name,id:input_id});$(elem.container).append(elem.button).append(elem.result_area).append(elem.hidden);$(elem.button).append(elem.img);$(elem.result_area).append(elem.results).append(elem.navi);if(option.multiple){$(elem.container).addClass('sp_container_combo');$(elem.combo_input).addClass('sp_combo_input').before($(elem.element_box));var li=$('<li>').addClass('input_box');$(li).append($(elem.combo_input));$(elem.element_box).append($(li));if($(elem.combo_input).attr('placeholder'))$(elem.combo_input).attr('placeholder_bak',$(elem.combo_input).attr('placeholder'));}this.elem=elem;},_setButtonAttrDefault:function(){if(this.option.select_only){if($(this.elem.combo_input).val()!==''){if($(this.elem.hidden).val()!==''){$(this.elem.combo_input).attr('title',this.message.select_ok).removeClass(this.css_class.select_ng).addClass(this.css_class.select_ok);}else{$(this.elem.combo_input).attr('title',this.message.select_ng).removeClass(this.css_class.select_ok).addClass(this.css_class.select_ng);}}else{$(this.elem.hidden).val('');$(this.elem.combo_input).removeAttr('title').removeClass(this.css_class.select_ng);}}$(this.elem.button).attr('title',this.message.get_all_btn);},_setInitRecord:function(){var self=this;if(this.option.init_record===false)return;$(self.elem.hidden).val(self.option.init_record);if(typeof self.option.source=='object'){var data=new Array();var keyarr=self.option.init_record.split(',');$.each(keyarr,function(index,row){for(var i=0;i<self.option.source.length;i++){if(self.option.source[i][self.option.primary_key]==row){data.push(self.option.source[i]);break;}}});if(!self.option.multiple&&data.length>1)data=null;self._afterInit(self,data);}else{$.ajax({dataType:'json',url:self.option.source,data:{db_table:self.option.db_table,pkey_name:self.option.primary_key,pkey_val:self.option.init_record},success:function(json){self._afterInit(self,json);},error:function(jqXHR,textStatus,errorThrown){self._ajaxErrorNotify(self,errorThrown);}});}},_afterInit:function(self,data){if(!data)return;if(!$.isArray(data))data=[data];if(self.option.multiple){$(self.elem.combo_input).val('');$.each(data,function(i,row){var item={text:row[self.option.field],value:row[self.option.primary_key]};if(!self._isAlreadySelected(self,item))self._addNewTag(self,item);});self._tagValuesSet(self);self._inputResize(self);}else{var row=data[0];$(self.elem.combo_input).val(row[self.option.field]);$(self.elem.hidden).val(row[self.option.primary_key]);self.prop.prev_value=row[self.option.field];if(self.option.select_only){$(self.elem.combo_input).attr('title',self.message.select_ok).removeClass(self.css_class.select_ng).addClass(self.css_class.select_ok);}}},_ehButton:function(){var self=this;$(self.elem.button).mouseup(function(ev){if($(self.elem.result_area).is(':hidden')&&!$(self.elem.combo_input).prop('disabled')){$(self.elem.combo_input).focus();}else{self._hideResults(self);}ev.stopPropagation();}).mouseover(function(){$(self.elem.button).addClass(self.css_class.btn_on).removeClass(self.css_class.btn_out);}).mouseout(function(){$(self.elem.button).addClass(self.css_class.btn_out).removeClass(self.css_class.btn_on);}).mouseout();},_ehComboInput:function(){var self=this;$(self.elem.combo_input).keyup(function(ev){self._processKey(self,ev);}).focus(function(e){if($(self.elem.result_area).is(':hidden')){e.stopPropagation();self.prop.first_show=true;self.prop.page_move=false;self.prop.is_suggest=false;self._suggest(self);}}).click(function(){self._setCssFocusedInput(self);});if(self.option.multiple){$(self.elem.element_box).click(function(e){var srcEl=e.target||e.srcElement;if($(srcEl).is('ul'))$(self.elem.combo_input).focus();});$(self.elem.element_box).on('click','span.tag_close',function(){var li=$(this).closest('li');var key=$(li).attr('itemvalue');var keys=$(self.elem.hidden).val();if($.type(key)!='undefined'&&keys){var keyarr=keys.split(',');var index=$.inArray(key.toString(),keyarr);if(index!=-1){keyarr.splice(index,1);$(self.elem.hidden).val(keyarr.toString());}}$(li).remove();self._inputResize(self);});self._inputResize(self);}},_ehWhole:function(){var self=this;$(self.elem.container).mousedown(function(){var thisindex=$('div.sp_container').index(this);var lastindex=$(document.body).data(constants.objStatusIndex);if(lastindex!=undefined&&thisindex!=lastindex){$(document.body).data(constants.objStatusKey,false);}else{$(document.body).data(constants.objStatusKey,true);}$(document.body).data(constants.objStatusIndex,thisindex);});$(document).off('mousedown.selectPage').on('mousedown.selectPage',function(e){if($(document.body).data(constants.objStatusKey))$(document.body).data(constants.objStatusKey,false);else{var cleanContent=function(obj){$(obj.elem.combo_input).val('');if(!obj.option.multiple)$(obj.elem.hidden).val('');};$('div.sp_container').each(function(){var d=$(this).data(constants.dataKey);if($(this).hasClass(d.css_class.container_open)){if(!$(d.elem.combo_input).val()&&$(d.elem.hidden).val()&&!d.option.multiple){d.prop.page_all=1;cleanContent(d);d._hideResults(d);return true;}if($('li',$(d.elem.results)).size()>0){if(d.option.auto_fill_result){if($('li.sp_selected',$(d.elem.results)).size()>0){d._hideResults(d);}else if($('li.sp_over',$(d.elem.results)).size()>0){if($(d.elem.hidden).val())d._hideResults(d);else d._selectCurrentLine(d,true);}else if(d.option.auto_select_first){if($(d.elem.hidden).val())d._hideResults(d);else{d._nextLine(d);d._selectCurrentLine(d,true);}}else{d._hideResults(d);}}else d._hideResults(d);}else{if(d.option.no_result_clean)cleanContent(d);else{if(!d.option.multiple)$(d.elem.hidden).val('');}d._hideResults(d);}}});}});},_ehResults:function(){var self=this;$(self.elem.results).children('li').mouseover(function(){if(self.prop.key_select){self.prop.key_select=false;return;}$(self.elem.results).children('li').removeClass(self.css_class.select);$(this).addClass(self.css_class.select);self._setCssFocusedResults(self);}).click(function(e){if(self.prop.key_select){self.prop.key_select=false;return;}e.preventDefault();e.stopPropagation();self._selectCurrentLine(self,false);});},_ehNaviPaging:function(self){$('li.csFirstPage',$(self.elem.navi)).off('click').on('click',function(ev){$(self.elem.combo_input).focus();ev.preventDefault();self._firstPage(self);});$('li.csPreviousPage',$(self.elem.navi)).off('click').on('click',function(ev){$(self.elem.combo_input).focus();ev.preventDefault();self._prevPage(self);});$('li.csNextPage',$(self.elem.navi)).off('click').on('click',function(ev){$(self.elem.combo_input).focus();ev.preventDefault();self._nextPage(self);});$('li.csLastPage',$(self.elem.navi)).off('click').on('click',function(ev){$(self.elem.combo_input).focus();ev.preventDefault();self._lastPage(self);});},_ajaxErrorNotify:function(self,errorThrown){alert(self.message.ajax_error);},_scrollWindow:function(self,enforce){var current_result=self._getCurrentLine(self);var target_top=(current_result&&!enforce)?current_result.offset().top:$(self.elem.container).offset().top;var target_size;self.prop.size_li=$(self.elem.results).children('li:first').outerHeight();target_size=self.prop.size_li;var client_height=$(window).height();var scroll_top=$(window).scrollTop();var scroll_bottom=scroll_top+client_height-target_size;var gap;if($(current_result).length){if(target_top<scroll_top||target_size>client_height){gap=target_top-scroll_top;}else if(target_top>scroll_bottom){gap=target_top-scroll_bottom;}else{return;}}else if(target_top<scroll_top)gap=target_top-scroll_top;window.scrollBy(0,gap);},_setCssFocusedInput:function(self){$(self.elem.results).addClass(self.css_class.re_off);$(self.elem.combo_input).removeClass(self.css_class.input_off);},_setCssFocusedResults:function(self){$(self.elem.results).removeClass(self.css_class.re_off);$(self.elem.combo_input).addClass(self.css_class.input_off);},_checkValue:function(self){var now_value=$(self.elem.combo_input).val();if(now_value!=self.prop.prev_value){self.prop.prev_value=now_value;self.prop.first_show=false;if(self.option.select_only)self._setButtonAttrDefault();self.prop.page_suggest=1;self.prop.is_suggest=true;self._suggest(self);}},_processKey:function(self,e){if(($.inArray(e.keyCode,[27,38,40,9])>-1&&$(self.elem.result_area).is(':visible'))||($.inArray(e.keyCode,[37,39,13,9])>-1&&self._getCurrentLine(self))||(e.keyCode==40)){e.preventDefault();e.stopPropagation();e.cancelBubble=true;e.returnValue=false;switch(e.keyCode){case 37:if(e.shiftKey)self._firstPage(self);else self._prevPage(self);break;case 38:self.prop.key_select=true;self._prevLine(self);break;case 39:if(e.shiftKey)self._lastPage(self);else self._nextPage(self);break;case 40:if($(self.elem.results).children('li').length){self.prop.key_select=true;self._nextLine(self);}else{self.prop.is_suggest=false;self._suggest(self);}break;case 9:self.prop.key_paging=true;self._selectCurrentLine(self,true);break;case 13:self._selectCurrentLine(self,true);break;case 27:self.prop.key_paging=true;self._hideResults(self);break;}}else{if(e.keyCode!=16)self._setCssFocusedInput(self);self._inputResize(self);self._checkValue(self);}},_abortAjax:function(self){if(self.prop.xhr){self.prop.xhr.abort();self.prop.xhr=false;}},_suggest:function(self){var q_word;q_word=(self.prop.first_show)?'':$.trim($(self.elem.combo_input).val());q_word=q_word.split(/[\s ]+/);self._abortAjax(self);self._setLoading(self);if(self.prop.is_paging){var obj=self._getCurrentLine(self);self.prop.is_paging=(obj)?$(self.elem.results).children('li').index(obj):-1;}else if(!self.prop.is_suggest){self.prop.is_paging=0;}var which_page_num=self.prop.page_all;if(typeof self.option.source=='object')self._searchForJson(self,q_word,which_page_num);else self._searchForDb(self,q_word,which_page_num);},_setLoading:function(self){$(self.elem.navi_info).text(self.message.loading);if($(self.elem.results).html()===''){$(self.elem.navi).children('p').empty();self._calcWidthResults(self);$(self.elem.container).addClass(self.css_class.container_open);}},_searchForDb:function(self,q_word,which_page_num){var _paramsFunc=self.option.params;var _params={};var searchKey=self.option.search_field;var _orgParams={q_word:q_word,pageNumber:which_page_num,pageSize:self.option.per_page,and_or:self.option.and_or,order_by:self.option.order_by,db_table:self.option.db_table};_orgParams[searchKey]=q_word[0];if(_paramsFunc&&$.isFunction(_paramsFunc)){var result=_paramsFunc();if(result&&$.isPlainObject(result)){_params=$.extend({},_orgParams,result);}else _params=_orgParams;}else _params=_orgParams;self.prop.xhr=$.eAjax({dataType:'json',url:self.option.source,data:_params,success:function(returnData){if(!returnData||!$.isPlainObject(returnData)){self._hideResults(self);self._ajaxErrorNotify(self,errorThrown);return;}var json={};json.originalResult=returnData.gridResult.list;json.cnt_whole=returnData.gridResult.totalRow;json.candidate=[];json.primary_key=[];if(typeof json.originalResult!='object'){self.prop.xhr=null;self._notFoundSearch(self);return;}json.cnt_page=json.originalResult.length;for(i=0;i<json.cnt_page;i++){for(var key in json.originalResult[i]){if(key==self.option.primary_key){json.primary_key.push(json.originalResult[i][key]);}if(key==self.option.field){json.candidate.push(json.originalResult[i][key]);}}}self._prepareResults(self,json,q_word,which_page_num);},error:function(jqXHR,textStatus,errorThrown){if(textStatus!='abort'){self._hideResults(self);self._ajaxErrorNotify(self,errorThrown);}},complete:function(){self.prop.xhr=null;}});},_searchForJson:function(self,q_word,which_page_num){var matched=[];var esc_q=[];var sorted=[];var json={};var i=0;var arr_reg=[];do{esc_q[i]=q_word[i].replace(/\W/g,'\\$&').toString();arr_reg[i]=new RegExp(esc_q[i],'gi');i++;}while(i<q_word.length);for(i=0;i<self.option.source.length;i++){var flag=false;var row=self.option.source[i];for(var j=0;j<arr_reg.length;j++){var itemText=row[self.option.field];if(self.option.format_item&&$.isFunction(self.option.format_item))itemText=self.option.format_item(row);if(itemText.match(arr_reg[j])){flag=true;if(self.option.and_or=='OR')break;}else{flag=false;if(self.option.and_or=='AND')break;}}if(flag)matched.push(row);}if(matched.length===undefined){self._notFoundSearch(self);return;}json.cnt_whole=matched.length;var reg1=new RegExp('^'+esc_q[0]+'$','gi');var reg2=new RegExp('^'+esc_q[0],'gi');var matched1=[];var matched2=[];var matched3=[];for(i=0;i<matched.length;i++){if(matched[i][self.option.order_by[0][0]].match(reg1)){matched1.push(matched[i]);}else if(matched[i][self.option.order_by[0][0]].match(reg2)){matched2.push(matched[i]);}else{matched3.push(matched[i]);}}if(self.option.order_by[0][1].match(/^asc$/i)){matched1=self._sortAsc(self,matched1);matched2=self._sortAsc(self,matched2);matched3=self._sortAsc(self,matched3);}else{matched1=self._sortDesc(self,matched1);matched2=self._sortDesc(self,matched2);matched3=self._sortDesc(self,matched3);}sorted=sorted.concat(matched1).concat(matched2).concat(matched3);if(!self.prop.page_move){if(!self.option.multiple){var currentValue=$(self.elem.hidden).val();if(typeof(currentValue)!='undefined'&&$.trim(currentValue)!=''){var index=0;$.each(sorted,function(i,row){if(row[self.option.primary_key]==currentValue){index=i+1;return false;}});which_page_num=Math.ceil(index/self.option.per_page);if(which_page_num<1)which_page_num=1;self.prop.page_all=which_page_num;}}}else{if(sorted.length<=((which_page_num-1)*self.option.per_page)){which_page_num=1;self.prop.page_all=1;}}var start=(which_page_num-1)*self.option.per_page;var end=start+self.option.per_page;json.originalResult=[];for(i=start;i<end;i++){if(sorted[i]===undefined)break;json.originalResult.push(sorted[i]);for(var key in sorted[i]){if(key==self.option.primary_key){if(json.primary_key===undefined)json.primary_key=[];json.primary_key.push(sorted[i][key]);}if(key==self.option.field){if(json.candidate===undefined)json.candidate=[];json.candidate.push(sorted[i][key]);}}}if(json.candidate===undefined)json.candidate=[];json.cnt_page=json.candidate.length;self._prepareResults(self,json,q_word,which_page_num);},_sortAsc:function(self,arr){arr.sort(function(a,b){return a[self.option.order_by[0][0]].localeCompare(b[self.option.order_by[0][0]]);});return arr;},_sortDesc:function(self,arr){arr.sort(function(a,b){return b[self.option.order_by[0][0]].localeCompare(a[self.option.order_by[0][0]]);});return arr;},_notFoundSearch:function(self){$(self.elem.navi_info).text(self.message.not_found);$(self.elem.navi_p).hide();$(self.elem.results).empty();self._calcWidthResults(self);$(self.elem.container).addClass(self.css_class.container_open);self._setCssFocusedInput(self);},_prepareResults:function(self,json,q_word,which_page_num){self._setNavi(self,json.cnt_whole,json.cnt_page,which_page_num);if(!json.primary_key)json.primary_key=false;if(self.option.select_only&&json.candidate.length===1&&json.candidate[0]==q_word[0]){$(self.elem.hidden).val(json.primary_key[0]);this._setButtonAttrDefault();}var is_query=false;if(q_word&&q_word.length>0&&q_word[0])is_query=true;self._displayResults(self,json,is_query);if(self.prop.is_paging===false)self._setCssFocusedInput(self);else{if(!self.option.multiple){var liSelected=$('li.sp_selected',$(self.elem.results));if($(liSelected).size()==0){var idx=self.prop.is_paging;var limit=$(self.elem.results).children('li').length-1;if(idx>limit)idx=limit;var obj=$(self.elem.results).children('li').eq(idx);$(obj).addClass(self.css_class.select);}else $(liSelected).addClass(self.css_class.select);}self.prop.is_paging=false;self._setCssFocusedResults(self);}},_setNavi:function(self,cnt_whole,cnt_page,page_num){var buildPageNav=function(self,pagebar,page_num,last_page){if($('li',$(pagebar)).size()==0){$(pagebar).empty();var btnclass='',isNewFontAwesome=true;$.each(document.styleSheets,function(i,n){if(n&&n.href&&n.href.indexOf('font-awesome-3.2.1')!=-1){isNewFontAwesome=false;return false;}});var iconFist='fa fa-step-backward',iconPrev='fa fa-backward',iconNext='fa fa-forward',iconLast='fa fa-step-forward';if(!isNewFontAwesome){iconFist='icon-step-backward';iconPrev='icon-backward';iconNext='icon-forward';iconLast='icon-step-forward';}if(page_num==1)btnclass=' disabled ';$(pagebar).append('<li class="csFirstPage'+btnclass+'" title="'+self.message.first_title+'" ><a href="javascript:void(0);"> <i class="'+iconFist+'"></i> </a></li>');$(pagebar).append('<li class="csPreviousPage'+btnclass+'" title="'+self.message.prev_title+'" ><a href="javascript:void(0);"><i class="'+iconPrev+'"></i></a></li>');var pageInfo=''+page_num+' 页(共'+last_page+'页)';$(pagebar).append('<li class="disabled pageInfoBox"><a href="javascript:void(0);"> '+pageInfo+' </a></li>');if(page_num==last_page)btnclass=' disabled ';else btnclass='';$(pagebar).append('<li class="csNextPage'+btnclass+'" title="'+self.message.next_title+'" ><a href="javascript:void(0);"><i class="'+iconNext+'"></i></a></li>');$(pagebar).append('<li class="csLastPage'+btnclass+'" title="'+self.message.last_title+'" ><a href="javascript:void(0);"> <i class="'+iconLast+'"></i> </a></li>');}};var pagebar=$('ul',$(self.elem.navi));var last_page=Math.ceil(cnt_whole/self.option.per_page);if(last_page==0)page_num=0;else{if(page_num==0)page_num=1;}buildPageNav(self,pagebar,page_num,last_page);var pageInfoBox=$('li.pageInfoBox',$(pagebar));var pageInfo=''+page_num+' 页(共'+last_page+'页)';$(pageInfoBox).html('<a href="javascript:void(0);"> '+pageInfo+' </a>');var dClass='disabled';var first=$('li.csFirstPage',$(pagebar));var previous=$('li.csPreviousPage',$(pagebar));var next=$('li.csNextPage',$(pagebar));var last=$('li.csLastPage',$(pagebar));if(page_num==1||page_num==0){if(!$(first).hasClass(dClass))$(first).addClass(dClass);if(!$(previous).hasClass(dClass))$(previous).addClass(dClass);}else{if($(first).hasClass(dClass))$(first).removeClass(dClass);if($(previous).hasClass(dClass))$(previous).removeClass(dClass);}if(page_num==last_page||last_page==0){if(!$(next).hasClass(dClass))$(next).addClass(dClass);if(!$(last).hasClass(dClass))$(last).addClass(dClass);}else{if($(next).hasClass(dClass))$(next).removeClass(dClass);if($(last).hasClass(dClass))$(last).removeClass(dClass);}if(last_page>1){if(self.prop.is_suggest)self.prop.max_suggest=last_page;else self.prop.max_all=last_page;self._ehNaviPaging(self);}else{}},_displayResults:function(self,json,is_query){$(self.elem.results).empty();var arr_candidate=json.candidate;var arr_primary_key=json.primary_key;var keystr=$(self.elem.hidden).val();var keyArr=keystr?keyArr=keystr.split(','):new Array();for(var i=0;i<arr_candidate.length;i++){var itemText='';if(self.option.format_item&&$.isFunction(self.option.format_item)){try{itemText=self.option.format_item(json.originalResult[i]);}catch(e){console.error('formatItem内容格式化函数内容设置不正确!');itemText=arr_candidate[i];}}else itemText=arr_candidate[i];var list=$('<li>').html(itemText).attr({pkey:arr_primary_key[i],title:itemText});if($.inArray(arr_primary_key[i].toString(),keyArr)!=-1){$(list).addClass(self.css_class.selected);}$(list).data('dataObj',json.originalResult[i]);$(self.elem.results).append(list);}self._calcWidthResults(self);$(self.elem.container).addClass(self.css_class.container_open);self._ehResults();if(is_query&&arr_candidate.length>0&&self.option.auto_select_first)self._nextLine(self);$(self.elem.button).attr('title',self.message.close_btn);},_calcWidthResults:function(self){$(self.elem.result_area).show(1,function(){if($(self.elem.container).css('position')=='static'){var offset=$(self.elem.combo_input).offset();$(self.elem.result_area).css({top:offset.top+$(self.elem.combo_input).outerHeight()+'px',left:offset.left+'px'});}else{var browserWidth=document.body.clientWidth;var browserHeight=document.body.clientHeight;var offset=$(self.elem.container).offset();var listWidth=$(self.elem.result_area).outerWidth();var listHeight=$(self.elem.result_area).outerHeight();var defaultLeft=self.option.multiple?-1:0;var left=(offset.left+listWidth)>browserWidth?-(listWidth-$(self.elem.container).outerWidth()):defaultLeft;var screenTop=offset.top-$(window).scrollTop();var top=0;if((screenTop+$(self.elem.container).outerHeight()+listHeight)>browserHeight){top=-(listHeight+1);$(self.elem.result_area).removeClass('shadowUp shadowDown').addClass('shadowUp');}else{top=self.option.multiple?$(self.elem.container).innerHeight()+1:$(self.elem.container).outerHeight();$(self.elem.result_area).removeClass('shadowUp shadowDown').addClass('shadowDown');}$(self.elem.result_area).css({top:top+'px',left:left+'px'});}});},_hideResults:function(self){if(self.prop.key_paging){self._scrollWindow(self,true);self.prop.key_paging=false;}self._setCssFocusedInput(self);if(self.option.auto_fill_result){}$(self.elem.results).empty();$(self.elem.result_area).hide();$(self.elem.container).removeClass(self.css_class.container_open);self._abortAjax(self);self._setButtonAttrDefault();},_firstPage:function(self){if(self.prop.page_all>1){self.prop.page_all=1;self.prop.is_paging=true;self.prop.page_move=true;self._suggest(self);}},_prevPage:function(self){if(self.prop.page_all>1){self.prop.page_all--;self.prop.is_paging=true;self.prop.page_move=true;self._suggest(self);}},_nextPage:function(self){if(self.prop.page_all<self.prop.max_all){self.prop.page_all++;self.prop.is_paging=true;self.prop.page_move=true;self._suggest(self);}},_lastPage:function(self){if(self.prop.page_all<self.prop.max_all){self.prop.page_all=self.prop.max_all;self.prop.is_paging=true;self.prop.page_move=true;self._suggest(self);}},_goPage:function(self,page){if(typeof(page)=='undefined')page=1;if(self.prop.page_all<self.prop.max_all){self.prop.page_all=page;self.prop.is_paging=true;self.prop.page_move=true;self._suggest(self);}},_selectCurrentLine:function(self,is_enter_key){self._scrollWindow(self,true);var current=self._getCurrentLine(self);if(current){if(!self.option.multiple){$(self.elem.combo_input).val($(current).text());$(self.elem.hidden).val($(current).attr('pkey'));}else{$(self.elem.combo_input).val('');var item={text:$(current).text(),value:$(current).attr('pkey')};if(!self._isAlreadySelected(self,item)){self._addNewTag(self,item);self._tagValuesSet(self);}}if(self.option.select_only)self._setButtonAttrDefault();if(self.option.bind_to){$(self.elem.combo_input).trigger(self.option.bind_to,$(current).data('dataObj'));}self.prop.prev_value=$(self.elem.combo_input).val();self._hideResults(self);}$(self.elem.combo_input).change();$(self.elem.combo_input).blur();self._setCssFocusedInput(self);self._inputResize(self);},_getCurrentLine:function(self){if($(self.elem.result_area).is(':hidden'))return false;var obj=$(self.elem.results).children('li.'+self.css_class.select);if($(obj).length)return obj;else return false;},_isAlreadySelected:function(self,item){var isExist=false;if(item.value){var keys=$(self.elem.hidden).val();if(keys){var karr=keys.split(',');if(karr&&karr.length>0&&$.inArray(item.value,karr)!=-1)isExist=true;}}return isExist;},_addNewTag:function(self,item){if(!self.option.multiple||!item)return;var tmp=self.template.tag.content;tmp=tmp.replace(self.template.tag.textKey,item.text);tmp=tmp.replace(self.template.tag.valueKey,item.value);$(self.elem.combo_input).closest('li').before($(tmp));},_tagValuesSet:function(self){if(!self.option.multiple)return;var tags=$('li.selected_tag',$(self.elem.element_box));if(tags&&$(tags).size()>0){var result=new Array();$.each(tags,function(i,li){var v=$(li).attr('itemvalue');if($.type(v)!='undefined')result.push(v);});if(result.length>0){$(self.elem.hidden).val(result.join(','));}}},_inputResize:function(self){if(!self.option.multiple)return;var width='';var inputLi=self.elem.combo_input.closest('li');var setDefaultSize=function(self,inputLi){inputLi.removeClass('full_width');var minimumWidth=self.elem.combo_input.val().length+1;var width=(minimumWidth*0.75)+'em';self.elem.combo_input.css('width',width);self.elem.combo_input.removeAttr('placeholder');};if($('li.selected_tag',$(self.elem.element_box)).size()==0){if(self.elem.combo_input.attr('placeholder_bak')){if(!inputLi.hasClass('full_width'))inputLi.addClass('full_width');self.elem.combo_input.attr('placeholder',self.elem.combo_input.attr('placeholder_bak'));}else setDefaultSize(self,inputLi);}else setDefaultSize(self,inputLi);},_nextLine:function(self){var obj=self._getCurrentLine(self);var idx;if(!obj)idx=-1;else{idx=$(self.elem.results).children('li').index(obj);$(obj).removeClass(self.css_class.select);}idx++;if(idx<$(self.elem.results).children('li').length){var next=$(self.elem.results).children('li').eq(idx);$(next).addClass(self.css_class.select);self._setCssFocusedResults(self);}else self._setCssFocusedInput(self);self._scrollWindow(self,false);},_prevLine:function(self){var obj=self._getCurrentLine(self);var idx;if(!obj)idx=$(self.elem.results).children('li').length;else{idx=$(self.elem.results).children('li').index(obj);$(obj).removeClass(self.css_class.select);}idx--;if(idx>-1){var prev=$(self.elem.results).children('li').eq(idx);$(prev).addClass(self.css_class.select);self._setCssFocusedResults(self);}else self._setCssFocusedInput(self);self._scrollWindow(self,false);}});})(window.jQuery);
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化