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

var $ = require('jquery'),
    security = require('../plugin/security'),
    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 $historySearch = $('.history-search');

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('');
    $historySearch.hide();
    $clearHistory.hide();

    window.rePosFooter();
});

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

$('#search').on('touchend', function() {
    if (security.hasDangerInput()) {
        return false;
    }
    $(this).closest('form').submit();
    return false;
});

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

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

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

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

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

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

writeSearch.bindWirteLocal($form);