search.js 2.69 KB
/**
 * 公共头部
 * @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);
});