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

var $ = require('jquery');

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

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

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

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

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

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

var ranToken = writeSearch.getRanToken();

$clearHistory.bind('tap', function() {
    localStorage.removeItem('historys');

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

$input.bind('input', function() {
    if ($input.val() === '') {
        $clear.addClass('hide');
    } else {
        $clear.removeClass('hide');
    }
});

$clear.bind('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);