search-list-extra.js 2.66 KB
import Page from 'yoho-page';
import Tip from 'plugin/tip';
import maybeLike from 'channel/maybe-like';

class SearchListExtra extends Page {
    constructor() {
        super();

        this.selector = {
            input: $('#search-input').find('input[name="query"]'),
            clear: $('#search-input .clear-input'),
            buriedpoint: $('.buriedpoint'),
            search: $('#search')
        };

        this.selector.clear.on('click', () => {
            this.selector.input.val('').trigger('input');
        });

        this.init();
    }

    init() {
        maybeLike({recpose: 100101, isExecute: true});
        this.inputAction();
    }

    /**
     * 搜索输入联动
     */
    inputAction() {
        let $searchAssociate = $('.search-associate');
        let $icon = $('.search-icon');
        let $searchItems = $('.search-items');

        this.selector.input.on('input', () => {
            if (this.selector.input.val() === '') {
                $icon.css('color', '#b2b2b2');
                this.selector.clear.addClass('hide');
                $searchAssociate.html('');
                $searchItems.show();
                $searchAssociate.hide();
            } else {
                $icon.css('color', '#666');
                this.selector.clear.removeClass('hide');
                $searchAssociate.show();
            }

            // 联动搜索
            $.ajax({
                url: '/product/search/fuzzyDatas',
                data: {
                    keyword: this.selector.input.val()
                },
                dataType: 'json',
                success: (data) => {
                    let ajaxHtml = '';
                    let i;

                    if (data.length > 0) {
                        for (i = 0; i < data.length; i++) {
                            ajaxHtml += '<li><span class="keyword">' + data[i].keyword + '</span><span class="count">' +
                                data[i].count + ' items<i class="iconfont">&#xe614;</i></span></li>';
                        }

                        $searchAssociate.html(ajaxHtml);
                        $searchItems.hide();
                    } else {
                        $searchAssociate.html('');
                    }

                    $searchAssociate.find('li').on('click', event => {
                        this.selector.buriedpoint.val($(event.currentTarget).find('.keyword').html());
                        this.selector.search.closest('form').submit();
                    });
                },
                error: () => {
                    Tip.show('网络断开连接了~');
                }
            });
        });
    }
}

export default SearchListExtra;