一個基於jquey的自動完成與分頁

這是最近做搜索引擎寫的前臺頁面,全基於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 

發佈留言