欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

一个基于jquey的自动完成与分页

程序员文章站 2024-01-14 09:15:28
这是最近做搜索引擎写的前台页面,全基于JQuery的ajax完成,包括自动完成和自动分页 。数据交换使用的是json格式。     JS  ...

这是最近做搜索引擎写的前台页面,全基于JQuery的ajax完成,包括自动完成和自动分页 。数据交换使用的是json格式。
 
 
JS
  1 /**
  2  * @author hyjiacan
  3  */
  4 $(document).ready(function() {
  5     // 页面载入后焦点定位到搜索框中
  6     $('#keyword').trigger('focus');
  7     // 消除按钮点击时的虚线框
  8     $('#submit').focus(function() {
  9         $(this).trigger('blur');
 10     });
 11     // 返回当前浏览器名称
 12     var getBrowserName = function() {
 13         var bmap = new Array();
 14         $.each($.browser,
 15         function(k, v) {
 16             bmap.push(k);
 17         });
 18         return bmap[0];
 19     };
 20     // ajax获取下拉列表
 21     var $autocompletelist = $('<p/>');
 22     $autocompletelist.addClass('autocompletelist');
 23
 24     // 自动完成事件处理
 25     var lastVal = '';
 26     $('#keyword').keydown(function(e) {
 27         // 将回车默认提交更改为ajax提交
 28         if (e.keyCode == 13) {
 29             hideAutoComplete();
 30             $('#submit').trigger('click');
 31             return false;
 32         }
 33     });
 34     var hideAutoComplete = function() {
 35         // 移除自动完成下拉列表
 36         $('#container').remove($autocompletelist);
 37         $autocompletelist.empty();
 38         $autocompletelist.slideUp(100);
 39     };
 40     $('#keyword').attr('onpaste', function(){
 41         $(this).trigger('keyup');
 42     });
 43     $('#keyword').keyup(function(e) {
 44
 45         if ($(this).val().trim() && $(this).val() == lastVal) return;
 46         lastVal = $(this).val();
 47
 48         $('.autocompletelist span').remove();
 49         // 自动完成下拉列表定位
 50         var pos = $('#keyword').position();
 51         $autocompletelist.css({
 52             left: pos.left,
 53             top: pos.top + $('#keyword').height()
 54         });
 55         $autocompletelist.empty();
 56         $autocompletelist.show();
 57         // 获取自动完成信息
 58         if ($('#keyword').val()) {
 59             // 加上时间戳,以防止读取缓存数据
 60             $.getJSON('autoComplete', 'keyword=' + encodeURIComponent($('#keyword').val())+'&dt='+encodeURIComponent($.now()),
 61             function(data) {
 62                 var suggestion = data.suggestion;
 63                 var len = suggestion.length;
 64                 if (len == 0) return;
 65                 var items = suggestion.items;
 66                 for(var i=0;i<len;i++){
 67                     var k = '<em class="k">' + items[i].keyword + '</em>';
 68                     var r = '<em class="r">约 ' + items[i].results + ' 结果</em>';
 69                     var item = $('<span>' + k +r + '</span>');
 70                    
 71                     item.click(function(e) {
 72                         $('#keyword').val($(this).children('.k').text());
 73                         $('#submit').trigger('click');
 74                         hideAutoComplete();
 75                     });
 76                     $autocompletelist.append(item);
 77                 };
 78                 // 添加自动完成下拉列表到DOM中
 79                 $('body').append($autocompletelist);
 80                 $autocompletelist.slideDown(500);
 81             });
 82         } else {
 83             hideAutoComplete();
 84         }
 85     });
 86
 87     var P = {
 88         //总页数
 89         length: 0,
 90         // current page index
 91         cpi: 1,
 92         setCpi: function(val) {
 93             P.cpi = parseInt(val);
 94         },
 95         // AJAX获取页码对应页面数据
 96         get: function() {
 97             P.setCpi($(this).attr('index'));
 98             $(this).parent().children().css('background-color', '');
 99             $(this).css('background-color', '#666');
100             $.ajax({
101                 url: 'jpager',
102                 type: 'get',
103                 data: 'page=' + P.cpi,
104                 dataType: 'json',
105                 success: function(data) {
106                     $('#list').empty();
107                     var len = data.list.length;
108                     var items = data.list.items;
109                    
110                     for(var i=0;i<len;i++){
111                         var $item = $('<p/>');
112                         $item.addClass('item');
113                         var $title = $('<a href="'+items[i].url+'"'+' target="_blank">'+items[i].title+'</a>');
114                         $title.addClass('title');
115                         var $summary = $('<p/>').text(items[i].summary);
116                         $summary.addClass('summary');
117                         var $url = $('<a href="'+items[i].url+'"'+' target="_blank">'+items[i].url+'</a>');
118                         $url.addClass('url');
119                         var $date = $('<span/>').text(items[i].date);
120                         $date.addClass('date');
121                         $item.append($title).append($summary).append($url).append($date);
122                         $('#list').append($item);
123                     };
124                     P.split(P.length);
125                 }
126             });
127         },
128         /**
129              *  当分页页面大于10个的时候,默认只显示前10个页码
130              *    具体实施示例:
131              *    1 2 3 4 5 6 7 8 9 10
132              *    当在这种情况下点击页码,页面前移动n个单位(具体单位为将点击页码置于第5个为准),则当前显示的页码改变为(以点击8为例):
133              *    4 5 6 7 8 9 10 11 12 13
134              *    以此类推
135 */
136         split: function(len) {
137             // 清空原有页码
138             $('#page').html('');
139             $('#page').append($('<span id="first" index="1">首页</span>').click(P.get));
140
141             if (P.cpi >= 5) {
142                 if (P.cpi > P.length - 5) {
143                     for (var i = P.length - 9; i <= P.length; i++) {
144                         $('#page').append($('<span index="' + i + '">' + i + '</span>').click(P.get));
145                     }
146                 } else {
147                     var si = P.cpi - 4; //start index
148                     var ei = P.cpi + 5; // end index
149                     for (var i = si; i <= ei; i++) {
150                         $('#page').append($('<span index="' + i + '">' + i + '</span>').click(P.get));
151                     }
152                 }
153             } else {
154                 var ei = P.length > 10 ? 10 : P.length;
155                 for (var i = 1; i <= ei; i++) {
156                     $('#page').append($('<span index="' + i + '">' + i + '</span>').click(P.get));
157                 }
158             }
159             $('#page').append($('<span id="last" index="' + P.length + '">末页</span>').click(P.get));
160         }
161     };
162
163     // 在输入框外的地方点击鼠标就隐藏下拉列表
164     $(document).click(function(e){
165         if(e.target.id != 'keyword'){
166             hideAutoComplete();
167         }       
168     });
169     // 开始ajax搜索
170     $('#submit').click(function() {
171         if ($('#keyword').val().trim() == '') {
172             $('#page').slideUp(500);
173             $('#list').slideUp(300);
174             $('#split').slideUp(500);
175
176             return;
177         }
178         $('#logo').hide(1000);
179         hideAutoComplete();
180         $.ajax({
181             url: 'jsearch',
182             type: 'get',
183             data: 'dt=' + encodeURIComponent($.now()) + '&bs=' + encodeURIComponent(getBrowserName()) + '&keyword=' + encodeURIComponent($('#keyword').val().trim()),
184             dataType: 'json',
185             success: function(data) {
186                 $('#split').slideDown(500);
187                 $('#kw_result').text($('#keyword').val().trim());
188                
189                 var list = data.list;
190                 var len = data.length;
191                 $('#list_length').text(len);
192                
193                 if (len == 0) {
194                     return;
195                 }
196                 var items = list.items;
197                 $('#list').empty();
198                 for(var i=0;i<list.length;i++){
199                     var $item = $('<p/>');
200                     $item.addClass('item');
201                     var $title = $('<a href="'+items[i].url+'"'+' target="_blank">'+items[i].title+'</a>');
202                     $title.addClass('title');
203                     var $summary = $('<p/>').text(items[i].summary);
204                     $summary.addClass('summary');
205                     var $url = $('<a href="'+items[i].url+'"'+' target="_blank">'+items[i].url+'</a>');
206                     $url.addClass('url');
207                     var $date = $('<span/>').text(items[i].date);
208                     $date.addClass('date');
209                     $item.append($title).append($summary).append($url).append($date);
210                     $('#list').append($item);
211                 };
212
213                 $('#list').show();
214                 P.length = Math.ceil(len / 10);
215                 P.setCpi(1);
216                 P.split();
217             }
218         });
219     });
220 });


CSS
* {
    margin: 0;
    padding: 0;
    font-size: 14px;
    line-height: 14px;
    border: 0;
}

body {
    min-width: 640px;
}

#JSearch {
    width: 600px;
    margin-top: 20px;
}

#keyword {
    width: 480px;
    height: 32px;
}

#submit {
    width: 100px;
    height: 32px;
}

input {
    font-size: 1.5em;
    line-height: 1.5em;
    height: 1.5em;
    border: solid #ccc 1px;
}

#submit {
    cursor: pointer;
    background-color: #DDDDDD;
}

#submit:hover, #submit:focus {
    background-color: #666666;
    color: #cccccc;
}

.center {
    margin: 20px auto;
    display: block;
}

.autocompletelist {
    background-color: #FFFFFF;
    width: 480px;
    height: auto;
    font-size: 1.2em;
    line-height: 1.2em;
    border: 1px solid #AAAAAA;
    position: absolute;
    display: none;
}

.autocompletelist span {
    display: block;
    padding: 2px 2px;
}

.autocompletelist span:hover, .dropdownlist span:focus {
    background-color: #DDDDDD;
    cursor: pointer;
    font-weight:bold;
}
.autocompletelist .r {
    float:right;
    margin-right:10px;
}

#split {
    margin: 10px auto;
    padding: 2px 20px;
    color: #3333FF;;
    vertical-align:middle;
    background-color: #eeeeee;
    font-size: 1em;
    line-height: 1em;
    display: none;
    text-align:right;
}
#split em{
    font-weight:bold;
}
#list {
    margin: 20px 40px;
}

#list p {
    margin: 2em auto;
}

#page {
    margin: 20px 5px;
    text-align: center;
}

#page span {
    cursor: pointer;
    font-size: 1.2em;
    line-height: 1.2em;
    margin: 0 2px;
    padding: 6px 8px;
    background-color: #DDDDDD;
    border: solid 1px #AAAAAA;
}

#page span:hover, #page span:focus {
    background-color: #BBBBBB;
    border: solid 1px #AAAAAA;
}

#list {
    width:800px;
    margin:0 auto;
    background-color: #FAFAFA;
}
#list a, #list a:visited{
    color:#0000FF;
    text-decoration:none;
}
#list .item{
    border-top:5px solid #FFFFFF;
    border-bottom:5px solid #FFFFFF;
    margin:0px auto;
}
#list .title{
    font-size:1.2em;
    line-height:1.2em;
}
#list .title:hover {
    color:#FF0000;
}
#list .summary{
    font-size:0.8em;
}
#list .url{
    background-color: #F3F3F3;
}
#list .date{
    float:right;
    clear:both;
}


HTML页面
<!DOCTYPE HTML>
<html>
    <head>
        <meta type="Content-Type" content="text/html;charset=UTF-8">
        <title>Search - Just search</title>
        <link rel="stylesheet" type="text/css" href="css/jsearch.css">
        <link rel="stylesheet" type="text/css" href="css/result.css">
        <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
        <script type="text/javascript" src="js/jsearch.js" charset="UTF-8"></script>
    </head>

    <body>
        <p class="center">
            <img class="center" id="logo" src="image/jsearchlogo.png" alt="Just search" />
            <form class="center" id="JSearch">
                <input type="text" id="keyword" name="keyword" maxlength="80"
                    value="" autocomplete="off" />
                <input type="button" id="submit" value="JSearch" />
            </form>
        </p>
        <p id="split" class="center">
            Search for "
            <em id="kw_result"></em>
            ", about
            <span id="list_length"></span>
            results.
        </p>
        <p id="list" class="center"></p>
        <p id="page" class="center"></p>
    </body>
</html>

 

摘自  hyjiacan