search.js 1.61 KB
/**
 * 搜索JS
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2015/10/19
 */

var $ = require('jquery'),
    Hammer = require('yoho.hammer');

var $input = $('#search-input input');

var $clear = $('#search-input .clear-input');

var $icon = $('.search-icon');

var $form = $('#search-form');

var $history = $('.history');

var $clearHistory = $('#clear-history');

var writeSearch = require('./write-search');

var ranToken = writeSearch.getRanToken();

var chHammer, cHammer;

chHammer = new Hammer($clearHistory[0]);
chHammer.on('tap', function() {
    localStorage.removeItem('historys');

    $history.html('');
});

$input.on('input', function() {
    if ($input.val() === '') {
        $icon.css('color', '#b2b2b2');
        $clear.addClass('hide');
    } else {
        $icon.css('color', '#000');
        $clear.removeClass('hide');
    }
});
cHammer = new Hammer($clear[0]);
cHammer.on('tap', function() {
    $input.val('').trigger('input');
});

//初始化历史搜索的内容
(function() {
    var html = '',
        history,
        historys, i;

    if (localStorage) {
        historys = localStorage.getItem('historys');

        if (historys && historys.length > 0) {
            historys = historys.split(ranToken);
            for (i = 0; i < historys.length; i++) {
                history = historys[i];

                if (history === '') {
                    continue;
                }

                html += '<li><a href="/?query=' + history + '">' + history + '</li>';
            }

            $history.html(html);
            $clearHistory.removeClass('hide');
        }
    }
}());

writeSearch.bindWirteLocal($form);