用jquery实现类似google将搜索结果显示在下列列表中的方法

来源:互联网 发布:淘宝商城首页 编辑:程序博客网 时间:2024/05/24 07:08

 

js如下:

 

/**
 * 基于jQuery的类似Google搜索的提示列表
 * 调用方式:$(input).tips(options);
 * options: 参数选项
 *  url  JOSN 获取URL地址
 *  param  获取JOSN数据时提交的参数名   
 *  leftText  提示列表左边显示文字的JSON字段
 *  rightText  提示列表右边显示文字的JSON字段
 *  inputText  点击提示列表后显示在输入框内容的JSON字段
 *  rightTextLength: 50, // 右边数字最长的长度
 *  leftTextLength:50, // 左边数字最长的长度
 *  
 *  hiddenId  隐藏域id 可选
 *  hiddenText  隐藏域值 可选
 *  width  提示列表宽度,可选(超宽时自动加宽, 默认为300)
 *  selectClass 选中样式
 *
 * 要求返回的JSON数据格式为:
 *  [{key:value,key:value...},{key:value,key:value...},...]
 *
 * 支持:IE, Firefox
 * @version: 1.0
 *  初始版本
 *
 * @version: 2.0
 *  修复问题:1、禁止浏览器自动完成功能
 *      2、修复与其它JS兼容问题
 *      3、鼠标经过时显示手状图
 * @version: 2.1
 *  修复问题:按回车无效,已修改
 *  添加功能:左边及右边字数显示的限制,默认为20个字/字符
 */

(function($){
 var has_val_flag = false; //是否已选值
 var mouse_click_flag = false;
 $.tips = function(input, options){
  var $input = $(input);
  var $tipsList = $("#tips-list-div-" + $input.attr("id"));
  var $hiddenTips = $("#tips-list-hidden-div-" + $input.attr("id"));
  
  $input.attr({"autocomplete":"off"}); // 禁止浏览器自动完成功能
  //$input.focus(function(e){
  // getData(e);
  //});

  $input.blur(function(){
   if ($tipsList.is(':visible') && !has_val_flag && !mouse_click_flag){
    $currentSelect = getCurrentSelect();
    var first_child = $tipsList.children('ul').children('li:first-child');
    var pattern = $(first_child).text();
    var value = $.trim($input.val());
    if(value!=""){
     $(first_child).addClass(options.selectClass); 
     selectCurrent();
    }
   }
   
   if(options.hiddenId!=undefined && options.hiddenId!=null && options.hiddenId!=""){
    if( $input.val()=="" ){
     if(options.otherhidden!=""){
      var otherhidden = $input.prev("[name='"+options.otherhidden+"']");
      $(otherhidden).val("");
     }
     else{
      $("#"+options.hiddenId).val("");
     }
    }
    else{
     //if(!has_val_flag){
     // $("#"+options.hiddenId).val("");
     // $input.val("");
     // has_val_flag = false;
     //}
    }
   }
   if(options.otherfunction!=""){
    reflect_function(options.otherfunction);  //反射调用js function  ,可重写该js
   }
   
   //jQuery("#tips-list-div-" + $input.attr("id")).hide();
   //setTimeout("jQuery('#tips-list-div-" + $input.attr("id")+"').slideUp('slow')", 100);
  });

  $input.keydown(processKey);

  $input.keyup(getData);
  
  function processKey(e) {
   has_val_flag = false;
   if (testSpeKey(e) && ($tipsList.is(':visible') || getCurrentSelect())) {            
             if (e.preventDefault)
                 e.preventDefault();

    if (e.stopPropagation)
                 e.stopPropagation();
       e.cancelBubble = true;
          e.returnValue = false;
   
    switch(e.keyCode) { 
     case 38: // up
      prevSelect();
      break;   
     case 40: // down
      nextSelect();
      break;
     case 13: // 回车
      selectCurrent();
      break;
    }
   }
  }

  // 当前选中的li
  function getCurrentSelect() {   
   if (!$tipsList.is(':visible'))
    return false;
   
   var $currentSelect = $tipsList.children('ul').children('li.'+options.selectClass);
   if (!$currentSelect.length)
    $currentSelect = false; 
   
   return $currentSelect;
  }
  
  // 将当前选中li返回到 input 中
  function selectCurrent() {  
   $currentSelect = getCurrentSelect();
  
   if ($currentSelect) {  
    $input.val($currentSelect.attr("inputText"));
    if($currentSelect.attr("hidenId")!=undefined && $currentSelect.attr("hidenId")!=null && $currentSelect.attr("hidenId")!=""){
     if(options.otherhidden!=""){
      var otherhidden = $input.prev("[name='"+options.otherhidden+"']");
      $(otherhidden).val($currentSelect.attr("hiddenText"));
     }else{
      $("#"+$currentSelect.attr("hidenId")).val($currentSelect.attr("hiddenText"));
     }
    }
    if($currentSelect.attr("show_1_id")!=undefined && $currentSelect.attr("show_1_id")!=null && $currentSelect.attr("show_1_id")!=""){
     $("#"+$currentSelect.attr("show_1_id")).val($currentSelect.attr("show_1_text"));
    }
    if($currentSelect.attr("show_2_id")!=undefined && $currentSelect.attr("show_2_id")!=null && $currentSelect.attr("show_2_id")!=""){
     $("#"+$currentSelect.attr("show_2_id")).val($currentSelect.attr("show_2_text"));
    }
    if($currentSelect.attr("show_3_id")!=undefined && $currentSelect.attr("show_3_id")!=null && $currentSelect.attr("show_3_id")!=""){
     $("#"+$currentSelect.attr("show_3_id")).val($currentSelect.attr("show_3_text"));
    }
    if($currentSelect.attr("show_4_id")!=undefined && $currentSelect.attr("show_4_id")!=null && $currentSelect.attr("show_4_id")!=""){
     $("#"+$currentSelect.attr("show_4_id")).val($currentSelect.attr("show_4_text"));
    }
    has_val_flag = true;
    hiddenTips();
    $input.blur();
    $input.focus();
    event.keyCode = 9;
   }  
  }
  
  // 向下选择
  function nextSelect() {  
   $currentSelect = getCurrentSelect(); 
   if ($currentSelect)
    $currentSelect.removeClass(options.selectClass).next().addClass(options.selectClass);
   else
    $tipsList.children('ul').children('li:first-child').addClass(options.selectClass);  
  }
  
  // 向上选择
  function prevSelect() {  
   $currentResult = getCurrentSelect();
  
   if ($currentResult)
    $currentResult.removeClass(options.selectClass).prev().addClass(options.selectClass);
   else{
    $tipsList.children('ul').children('li:last-child').addClass(options.selectClass);   
   }

  }

  // 测试是否 特殊键
  function testSpeKey(e){   
   // handling up/down/escape requires results to be visible
   // handling enter/tab requires that AND a result to be selected
   if (/27$|38$|40$/.test(e.keyCode) || /^13$|^9$/.test(e.keyCode)) {            
             return true;
   }
  }

  // 通过AJAX获取json数据
  function getData(e){
   if(testSpeKey(e)){
    return;
   }
   if(options.ds!=""){
    alert("from local");
    return;
   }
   if(options.show!=""){
    if(options.otherval!=""){
     var param = options.param;
     $.ajax({
      type: "POST",
      url: options.url,
      data: options.param+"="+$("#"+options.otherval).val(),
      contentType: "application/x-www-form-urlencoded; charset=utf-8",
      dataType: "json",
      success: function(data){
       displayDiv(data);
      }
     });
    }
    else{
     var param = options.param;
     $.ajax({
      type: "POST",
      url: options.url,
      data: options.param+"="+$input.val(),
      contentType: "application/x-www-form-urlencoded; charset=utf-8",
      dataType: "json",
      success: function(data){
       displayDiv(data);
      }
     });
    }
   }
   else{
    if($input.val()!=""){
     var param = options.param;
     $.ajax({
      type: "POST",
      url: options.url,
      data: options.param+"="+$input.val(),
      contentType: "application/x-www-form-urlencoded; charset=utf-8",
      dataType: "json",
      success: function(data){
       displayDiv(data);
      }
     });
    }else{
     hiddenTips();
    }
   }

  }
  
  // 初始化提示列表 每次AJAX获取数据后调用
  function initTips(){
   $tipsList.find("ul").find("li").each(function(){
    $(this).mouseover(function(){
     mouse_click_flag = true;
     $(this).addClass(options.selectClass);
    });
    $(this).mouseout(function(){
     mouse_click_flag = false;
     $(this).removeClass(options.selectClass);
    });
    $(this).click(selectCurrent)
    //$(this).click(function(){})
   });
  }

  // 清除样式
  function cleanClass(){
   $tipsList.find("ul").find("li").each(function(){
    $(this).removeClass(options.selectClass);
   });
  }
  
  // 显示提示列表
  function showTips(html){
   $tipsList.html(html);
   $hiddenTips.html(html);
   var offset = $input.offset();
   var height = $input.outerHeight();
   $tipsList.css("top", offset.top + height);
   $tipsList.css("left", offset.left);   
   var width = options.width
   initTips(); 
   $hiddenTips.css("display", "block");
   $hiddenTips.find("li").each(function(){
    var span = $(this).find("span");
    var width1 = $(span[0]).width() +  $(span[1]).width() + 20;
    var width2 = $(this).width() + 20;
    var maxWidth = width1>width2?width1:width2;
    width = width>maxWidth?width:maxWidth;
   });
   $hiddenTips.css("display", "none");
   $tipsList.width(width);
   $tipsList.slideDown("fast"); 
   has_val_flag = false;
  }

  // 隐藏提示列表
  function hiddenTips(){
   $tipsList.slideUp("fast");
  }
  
  // 将JOSN数据生成DIV
  function displayDiv(json){
   eval("var json=("+json+")");
   var div = "<ul>";
   if(json.length<=0){
    div += "<li hidenId='' hiddenText='' inputText=''><span class='left'>无数据!</span><span class='right'></span></li>";
    div += "</ul>"; 
    showTips(div);
    return ;
   }
   if(json.length>100){
    div += "<li hidenId='' hiddenText='' inputText=''><span class='left'>数据太多,请缩小查询范围!</span><span class='right'></span></li>";
    div += "</ul>"; 
    showTips(div);
    return ;
   }
   for(var i=0;i<json.length;i++){
    div += "<li ";
    if(options.hiddenId!=null){
     div += " hidenId='"+options.hiddenId+"' hiddenText='"+eval("json[i]."+options.hiddenText)+"' ";
    }
    if(options.show_1_id!=null){
     div += " show_1_id='"+options.show_1_id+"' show_1_text='"+eval("json[i]."+options.show_1_text)+"' ";
    }
    if(options.show_1_id!=null){
     div += " show_2_id='"+options.show_2_id+"' show_2_text='"+eval("json[i]."+options.show_2_text)+"' ";
    }
    if(options.show_1_id!=null){
     div += " show_3_id='"+options.show_3_id+"' show_3_text='"+eval("json[i]."+options.show_3_text)+"' ";
    }
    if(options.show_1_id!=null){
     div += " show_4_id='"+options.show_4_id+"' show_4_text='"+eval("json[i]."+options.show_4_text)+"' ";
    }
    div += "inputText='"+eval("json[i]."+options.inputText)+"'>";

    var lText = eval("json[i]."+options.leftText);
    if(lText!=undefined && lText!=null && lText.length>options.leftTextLength){
     lText = lText.substring(0, options.leftTextLength) + "...";
    }
    div += "<span class='left'>" + (lText==null?"":lText) + "</span>";

    var rText = eval("json[i]."+options.rightText);
    if(rText!=undefined && rText!=null && rText.length>options.rightTextLength){
     rText = rText.substring(0, options.rightTextLength) + "...";
    }
    div += "<span class='right'>"+(rText==null?"":rText)+"</span>";
    div += "</span></li>";
   }
   div += "</ul>"; 
   showTips(div);
   if($.trim($input.val()) != ""){
    $tipsList.children('ul').children('li:first-child').addClass(options.selectClass);  
   }
  }
 }

 $.fn.tips = function(options){
  options = options || {};
  options.url = options.url || ""; // 获取JSON数据的url地址
  options.param = options.param || this.id; // 获取JOSN数据时提交的参数名
  options.width = options.width || 300;
  options.rightTextLength = options.rightTextLength || 20;
  options.leftTextLength = options.leftTextLength || 20;

  options.leftText = options.leftText || "leftText"; // 提示列表左边显示文字的JSON字段
  options.rightText = options.rightText || "rightText"; // 提示列表右边显示文字的JSON字段
  options.inputText = options.inputText || "inputText"; // 点击提示列表后显示在输入框内容的JSON字段

  options.hiddenId = options.hiddenId || null; // 如有需要在隐藏域添加隐藏表单信息时,请填写隐藏域的 id
  options.hiddenText = options.hiddenText || "hiddenText"; // 如有需要在隐藏域添加隐藏表单信息时,隐藏域内容对应的JOSN字段
  options.selectClass = options.selectClass || "tips-div-hover"; // 选中样式
  
  options.otherval = options.otherval || "";  //获取指定的值
  options.show = options.show || "";  //立即显示
  options.otherfunction = options.otherfunction || "";  //调用函数
  options.ds = options.ds || "";  //数据源
  options.otherhidden = options.otherhidden || "";  //

  if($("#tips-list-div-" + this.attr("id")).attr("class")==undefined){
   $(document.body).append("<div id='tips-list-div-"+this.attr("id")+"' class='tips-div'>1</div>");
  }
  if($("#tips-list-hidden-div-" + this.attr("id")).attr("class")==undefined){
   $(document.body).append("<div id='tips-list-hidden-div-"+this.attr("id")+"' style='width:20px;visibility:hidden;display:none;'>1</div>");
  }

  this.each(function(){
   new $.tips(this, options);
  });
 
  return this;
 }
})(jQuery)


function reflect_function(type){
 
}

 

 

样式:

.tips-div {background:#fff;border:1px solid #7f9db9;position: absolute;display: none;margin:0px;padding:1px;}
.tips-div ul{margin:0px;padding:0px;list-style:none;cursor:pointer;}
.tips-div li{margin:0px;line-height:25px; height:25px; color:#05a; padding:1px 3px;}
.tips-div li span.left{margin:0px;padding:0px;float:left;display:block;}
.tips-div li span.right{margin:0px;padding:0px 0px 0px 10px;float:left;color:green;display:block;text-align:left;}

.tips-div-hover{background:#c8e3fc;}

 

 

调用示例(记得引入jquery的包): 
<input type="text" height="20px" id="myinput1" name="myinput1" value=""/>  
 
$("#myinput1").tips({  
             url: "json.html", // JOSN 获取URL地址  
             param: "myinput1", // 获取JOSN数据时提交的参数名             
             leftText: "text",// 提示列表左边显示文字的JSON字段  
            rightText: "text2", // 提示列表右边显示文字的JSON字段  
            inputText: "text", // 点击提示列表后显示在输入框内容的JSON字段  
     rightTextLength: 20, // 右边数字最长的长度
     leftTextLength:20, // 左边数字最长的长度
             hiddenId: "hid", // 隐藏域id 可选  
             hiddenText: "id", // 隐藏域值 可选  
            width: 100 // 提示列表宽度,可选  
         });