search.js
2.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* 公共头部
* @author: gxh<xuhui.ge@yoho.cn>
* @date: 2017/02/27
*/
var $ = require('yoho-jquery'),
handlebars = require('yoho-handlebars');
var $head = $('.head-wrapper'),
$searchForm = $('#search-form'), // 头部搜索栏
$searchKey = $searchForm.find('.search-key'),
$searchSug = $head.find('.search-suggest');
var defaultSearch = $('#defaultsearch').val() || '';
// 搜索历史提示
function searchSuggest(key) {
var param = {
return_type: 'jsonp',
keyword: key
};
$.getJSON('//search.yohobuy.com/product/search/suggest?callback=?', param, function(jsonData) {
var searchSuggestHtml;
if (jsonData.code === 200) {
if (jsonData.data && jsonData.data.length) {
searchSuggestHtml = handlebars.compile($('#search-suggest-tml').html() || '');
$searchSug.html(searchSuggestHtml(jsonData)).show();
} else {
$searchSug.hide();
}
}
});
}
function submitSearch() {
var searchKey = $searchKey.val();
searchKey = $.trim(searchKey.toLowerCase());
if (reg.test(searchKey) && searchKey !== '') {
location.href = 'http://search.yohobuy.com/error?query=' + searchKey;
} else {
if (searchKey === '') {
$('#query-key').val(defaultSearch);
}
$searchForm.submit();
}
}
$searchKey.keyup(function(e) {
var val = $.trim($(this).val()),
$child = $searchSug.find('li'),
$act = $searchSug.find('.action'),
$focus;
if (e.which > 36 && e.which < 41) {
if (e.which === 38) {
$focus = $act.prev();
if (!$act.length || !$focus.length) {
$focus = $child.eq($child.length - 1);
}
} else if (e.which === 40) {
$focus = $act.next();
if (!$act.length || !$focus.length) {
$focus = $child.eq(0);
}
} else {
return;
}
$child.removeClass('action');
$focus.addClass('action');
$(this).val($focus.find('.searchvalue').text());
} else if (e.which === 13) {
submitSearch();
} else {
if ($searchSug && $searchSug.length) {
val = val.replace(new RegExp('\'', 'gm'), ''); // 去掉特殊字符
searchSuggest(val);
}
}
}).focus(function() {
var val = $.trim($(this).val());
if (val === defaultSearch) {
$(this).val('');
}
$(this).css('color', '#333');
}).blur(function() {
var val = $.trim($(this).val());
if (val === '') {
$(this).val(defaultSearch).css('color', '#999');
}
setTimeout(function() {
$searchSug.hide();
}, 200);
});