Compare commits

...

2 Commits

Author SHA1 Message Date
qweasdzxc227 d737bee569 5.28.22.00
6 months ago
qweasdzxc227 618ebdb791 5.28.21.56
6 months ago

@ -1,8 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="Python 3.9 (article_spider)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="Python 3.9 (article_spider)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

@ -1,64 +1,86 @@
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import re
import scrapy
from scrapy.loader.processors import MapCompose, TakeFirst, Identity, Join
from scrapy.loader import ItemLoader
from ArticleSpider.models.es_types import ArticleType
from w3lib.html import remove_tags
class ArticlespiderItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass
def date_convert(value):
match_re = re.match('.*?(\d+.*)', value)
if match_re:
return match_re.group(1)
else:
return '1970-07-01'
class ArticleItemLoader(ItemLoader):
default_output_processor = TakeFirst()
class JobBoleArticleItem(scrapy.Item):
title = scrapy.Field() # 标题
create_date = scrapy.Field(
input_processor=MapCompose(date_convert)
) # 发布时间
url = scrapy.Field() # 链接
url_object_id = scrapy.Field() # 链接id
front_image_url = scrapy.Field(
output_processor=Identity()
) # 封面图
front_image_path = scrapy.Field() # 封面图路径
praise_nums = scrapy.Field() # 点赞数
comment_nums = scrapy.Field() # 评论数
fav_nums = scrapy.Field() # 收藏数
tags = scrapy.Field(
output_processor=Join(separator=',')
) # 标签
content = scrapy.Field() # 内容
def save_to_es(self):
article = ArticleType()
article.title = self['title']
article.create_date = self['create_date']
article.content = remove_tags(self['content'])
article.front_image_url = self['front_image_url']
if 'front_image_path' in self:
article.front_image_path = self['front_image_path']
article.praise_nums = self['praise_nums']
article.fav_nums = self['fav_nums']
article.comment_nums = self['comment_nums']
article.url = self['url']
article.tags = self['tags']
article.meta.id = self['url_object_id']
article.save()
return
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import re
import scrapy
from scrapy.loader.processors import MapCompose, TakeFirst, Identity, Join
from scrapy.loader import ItemLoader
from ArticleSpider.models.es_types import ArticleType
from w3lib.html import remove_tags
from elasticsearch_dsl.connections import connections
es = connections.create_connection(ArticleType._doc_type.using)
class ArticlespiderItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass
def gen_suggests(index, info_tuple):
# 根据字符串生成字符串搜索建议数组
used_words = set() # 去重
suggests = []
for text, weight in info_tuple:
if text:
# 调用es的analyze接口分析字符串
words = es.indices.analyze(index=index, analyzer='ik_max_word', params={'filter': ['lowercase']}, body=text)
anylyzed_words = set([r['token'] for r in words['tokens'] if len(r['token']) > 1])
new_words = anylyzed_words - used_words
else:
new_words = set()
if new_words:
suggests.append({'input': list(new_words), 'weight': weight})
return suggests
def date_convert(value):
match_re = re.match('.*?(\d+.*)', value)
if match_re:
return match_re.group(1)
else:
return '1970-07-01'
class ArticleItemLoader(ItemLoader):
default_output_processor = TakeFirst()
class JobBoleArticleItem(scrapy.Item):
title = scrapy.Field() # 标题
create_date = scrapy.Field(
input_processor=MapCompose(date_convert)
) # 发布时间
url = scrapy.Field() # 链接
url_object_id = scrapy.Field() # 链接id
front_image_url = scrapy.Field(
output_processor=Identity()
) # 封面图
front_image_path = scrapy.Field() # 封面图路径
praise_nums = scrapy.Field() # 点赞数
comment_nums = scrapy.Field() # 评论数
fav_nums = scrapy.Field() # 收藏数
tags = scrapy.Field(
output_processor=Join(separator=',')
) # 标签
content = scrapy.Field() # 内容
def save_to_es(self):
article = ArticleType()
article.title = self['title']
article.create_date = self['create_date']
article.content = remove_tags(self['content'])
article.front_image_url = self['front_image_url']
if 'front_image_path' in self:
article.front_image_path = self['front_image_path']
article.praise_nums = self['praise_nums']
article.fav_nums = self['fav_nums']
article.comment_nums = self['comment_nums']
article.url = self['url']
article.tags = self['tags']
article.meta.id = self['url_object_id']
article.suggest = gen_suggests(ArticleType._doc_type.index, ((article.title, 10), (article.tags, 7)))
article.save()
return

@ -1,12 +1,10 @@
# -*- coding: utf-8 -*-
__author__ = 'bobby'
from scrapy.cmdline import execute
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
execute(["scrapy", "crawl", "jobbole"])
# execute(["scrapy", "crawl", "zhihu"])
# execute(["scrapy", "crawl", "lagou"])
# -*- coding: utf-8 -*-
__author__ = 'bobby'
from scrapy.cmdline import execute
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
execute(["scrapy", "crawl", "jobbole"])

@ -0,0 +1,8 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="FacetManager">
<facet type="django" name="Django">
<configuration>
<option name="rootFolder" value="$MODULE_DIR$" />
<option name="settingsModule" value="LcvSearch/settings.py" />
<option name="manageScript" value="$MODULE_DIR$/manage.py" />
<option name="environment" value="&lt;map/&gt;" />
<option name="doNotUseTestRunner" value="false" />
<option name="trackFilePattern" value="migrations" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_CONFIGURATION" value="Django" />
<option name="TEMPLATE_FOLDERS">
<list>
<option value="$MODULE_DIR$/../LcvSearch\templates" />
</list>
</option>
</component>
</module>

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Black">
<option name="sdkName" value="Python 3.9 (lcv_search) (2)" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9 (lcv_search) (2)" project-jdk-type="Python SDK" />
</project>

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/LcvSearch.iml" filepath="$PROJECT_DIR$/.idea/LcvSearch.iml" />
</modules>
</component>
</project>

@ -0,0 +1,16 @@
"""
ASGI config for LcvSearch project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'LcvSearch.settings')
application = get_asgi_application()

@ -0,0 +1,127 @@
"""
Django settings for LcvSearch project.
Generated by 'django-admin startproject' using Django 4.2.13.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
import os.path
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-8vd6v)mxnxee#^3_n12)o3^4w$fg-1g@9p3y$_pa!&wh*@4pih'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'search.apps.SearchConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'LcvSearch.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates']
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'LcvSearch.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = 'static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

@ -0,0 +1,24 @@
"""
URL configuration for LcvSearch project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
path('', TemplateView.as_view(template_name='index.html'), name='index'),
]

@ -0,0 +1,16 @@
"""
WSGI config for LcvSearch project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'LcvSearch.settings')
application = get_wsgi_application()

@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'LcvSearch.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

@ -0,0 +1,6 @@
from django.apps import AppConfig
class SearchConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'search'

@ -0,0 +1,3 @@
from django.db import models
# Create your models here.

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.

@ -0,0 +1,50 @@
@charset "utf-8";
html{*overflow:auto;}
#hd{padding:20px 10px;}
.logo{float:left;margin-right:30px; height:33px;}
/*input搜索区域*/
.inputArea{float:left;position:relative;}
.inputArea .searchInput{border:1px solid #bfbfbf;padding:0 15px;outline:none;height:35px;*line-height:38px;width:350px; background:url(../img/inputbg.png);font-size:14px;}
.inputArea .searchButton{position:absolute;left:382px;top:0;*top:1px;*left:381px;width:106px;height:38px;background:url(../img/btn_min.png) no-repeat;border:none; cursor:pointer;}
/*返回搜索*/
.inputArea .back{position:absolute;font-size:14px;left:500px;top:12px;width:60px;text-decoration:underline;}
/*分界区域*/
.divsion{margin-bottom:24px;height:36px;background:#f9f9f9;border-bottom:1px solid #e0e0e0;}
/*高级搜索区域*/
.subfield{border-left:4px solid #9cc813;font-size:14px;font-weight:bold;padding:2px 0 2px 20px;}
.subfieldContent{padding-left:140px;padding-bottom:40px;}
.subfieldContent .advanceItem{padding-left:350px;margin-bottom:15px;padding-top:8px;padding-bottom:3px;}
.subfieldContent .advanceItem.keyWords{background:#f4f4f4;padding-top:18px;padding-bottom:3px;}
.subfieldContent .advanceItem dd{float:left;margin-left:-320px;}
.subfieldContent .advanceItem dd label{float:left;margin-right:40px;width:75px;font-weight:bold;}
.subfieldContent .advanceItem dd .impInfo{ font-weight:bold;}
.subfieldContent .advanceItem dd .tips{float:left;}
.subfieldContent .advanceItem dd p, .subfieldContent .advanceItem dt p{margin-bottom:10px;height:26px;}
.subfieldContent .advanceItem dt p input[type=text]{position:relative;top:-5px;line-height:26px;}
.subfieldContent .advanceItem dt{float:left;width:100%;}
.subfieldContent .advanceItem.keyWords dt input[type=text]{width:290px;height:26px;border:1px solid #bfbfbf;outline:none;}
/*自定义*/
.subfieldContent .advanceItem.time{height:30px;}
.subfieldContent .advanceItem .define{display:none;position:relative;*top:-3px;}
.subfieldContent .advanceItem.time input[type=text]{width:80px;height:18px;line-height:18px;border:1px solid #bfbfbf;outline:none;}
/*更多按钮*/
.more {float:left;}
.more:hover{text-decoration:none;}
.more .moreIcon{display:inline-block;position:relative;top:-1px;*top:-3px;left:2px;*left:-1px;width:9px;height:5px;background:url(../img/more.png);}
.more.show .moreIcon{background:url(../img/down.png);top:-2px;}
/*立即搜索样式*/
.subfieldContent .search{margin:45px 0 0 145px;width:130px;height:36px;background:url(../img/btnbg.png); font-weight:bold;border:none;border:1px solid #bfbfbf;line-height:36px;cursor:pointer;font-size:14px;}
/*联想下拉区域*/
.inputArea .dataList{display:none;position:absolute;left:0;top:42px;*top:43px;width:550px;padding:5px 0;background:#fff;border:1px solid #bfbfbf;border-top:none;}
.inputArea .dataList li{padding:2px 15px;font-size:14px;}
.inputArea .dataList li:hover{background:#f0f0f0;color:#0080cc;font-weight:bold;}

@ -0,0 +1,34 @@
@charset "utf-8";
html{*overflow:auto;}
#main{width:730px;margin:75px auto 0;}
#main h1.title{width:600px;}
#bd{margin-bottom:20px;}
.logo.large{margin:0px auto 10px auto;width:342px;height:144px;background: url(../img/logo.png) no-repeat center center;}
/*nav样式*/
.nav{margin-bottom:10px;}
.searchList{float:left;padding-left:5px;}
.searchList .searchItem{float:left;margin-right:15px;font-size:14px;padding:0 0 2px 2px;cursor:pointer;height:18px;}
.searchList .searchItem.current{color:#0080cc;border-bottom:2px solid #9cc813;font-weight:bold;}
/*input搜索区域*/
.inputArea{position:relative;margin-bottom:65px;}
.inputArea .searchInput{border:1px solid #bfbfbf;padding:0 15px;outline:none;height:40px;*height:39px;*line-height:40px;width:520px; background:url(../img/inputbg.png);font-size:14px;}
.inputArea .searchButton{position:absolute;left:550px;*left:552px;*top:1px;width:106px;height:42px;*height:41px;background:url(../img/seachbtn.png) no-repeat;border:none;cursor:pointer;}
/*高级搜索*/
.inputArea .advanced{position:absolute;font-size:14px;left:674px;top:12px;text-decoration:underline;}
/*联想下拉区域*/
.inputArea .dataList{display:none;position:absolute;left:0;top:42px;*top:43px;width:550px;padding:5px 0;background:#fff;border:1px solid #bfbfbf;border-top:none;}
.inputArea .dataList li{padding:2px 15px;font-size:14px;}
.inputArea .dataList li:hover{background:#f0f0f0;color:#0080cc;font-weight:bold;}
/*搜索历史区域*/
.historyArea{margin:0 auto;width:485px;}
.historyArea .history {margin-bottom:5px;}
.historyArea .history label{font-weight:bold;}
.historyArea .history a{margin-right:12px;}
/*版权信息*/
.foot{position:absolute;bottom:0px;width:100%;}
.foot .wrap{margin:0 auto;}
.foot .copyright{position:relative;top:-35px;color:#ababab;text-align:center;}

@ -0,0 +1,104 @@
@charset "utf-8";
html{*overflow:auto;}
#hd{padding:20px 10px;}
#bd{margin-bottom:40px;}
.logo{float:left;margin-right:30px; height:33px;}
/*input搜索区域*/
.inputArea{float:left;position:relative;}
.inputArea .searchInput{border:1px solid #bfbfbf;padding:0 15px;outline:none;height:35px;*line-height:35px;width:350px; background:url(../img/inputbg.png);font-size:14px;}
.inputArea .searchButton{position:absolute;left:382px;top:0;*top:1px;*left:381px;width:106px;height:38px;background:url(../img/btn_min.png) no-repeat;border:none;cursor:pointer;}
/*返回高级搜索*/
.inputArea .advanced{position:absolute;font-size:14px;left:500px;top:12px;width:60px;text-decoration:underline;}
/*分界区域,导航*/
.nav{margin-bottom:24px;height:31px;background:#f9f9f9;border-bottom:1px solid #e0e0e0;padding:5px 0 0 210px;}
.searchList{float:left;padding-left:5px;}
.searchList .searchItem{float:left;margin-right:15px;font-size:14px;padding:0 3px 2px 3px;cursor:pointer;height:26px; line-height:26px;}
.searchList .searchItem.current{color:#0080cc;border-bottom:3px solid #9cc813;font-weight:bold;}
.nav .tips{color:#969696;font-size:12px;line-height:24px;*line-height:26px;}
#container.sideBarHide .nav{padding-left:35px;}
/*#main区域样式*/
#main{padding:0 215px 0 182px;}
#main.sideBarHide{padding-left:10px;}
/*侧边栏搜索条件*/
.sideBar{position:relative;float:left;margin-left:-182px;width:182px;}
.sideBar .subfieldContext{margin-bottom:20px;padding-left:25px;}
.sideBar .subfieldContext li{margin-bottom:5px;cursor:pointer;}
.sideBar .subfieldContext input[type=text]{width:75px;}
.sideBar .unit{color:#787878;}
/*更多按钮*/
.sideBar .more a:hover{text-decoration:none;}
.sideBar .more .moreIcon{display:inline-block;position:relative;top:-1px;*top:-3px;left:2px;*left:-1px;width:9px;height:5px;background:url(../img/more.png);}
.sideBar .more.show .moreIcon{background:url(../img/down.png);top:-2px;}
.sideBar .reset{padding-left:25px;}
/*siderBar区域显隐控制*/
.sideBar .sideBarShowHide{position:absolute;right:0px;top:20px;height:177px;width:1px; background:url(../img/line.png) right;}
.sideBar .sideBarShowHide a{position:absolute;top:70px;left:-11px;display:inline-block;width:12px;height:31px;background:url(../img/lr.png);}
.sideBar .sideBarShowHide a:hover{background-position:0 -31px;}
/*左侧收起样式*/
#main.sideBarHide .sideBar{margin-left:-191px;*margin-left:-182px;}
#main.sideBarHide .sideBar .sideBarShowHide{-moz-transform:rotate(180deg); -o-transform:rotate(180deg); -webkit-transform:rotate(180deg); transform:rotate(180deg);}
#main.sideBarHide .sideBar .sideBarShowHide a{*background:url(../img/ll.png);}
#main.sideBarHide .sideBar .sideBarShowHide a:hover{*background-position:0 -31px;}
#main.sideBarHide .sideBar .sideBarShowHide{background:none;}
.resultArea{float:left;width:100%;}
.resultArea .resultTotal{position:relative;padding-left:30px;margin-bottom:20px;}
.resultArea .resultTotal .info{color:#9a9a9a;}
.resultArea .resultTotal .orderOpt{position:absolute;right:50px;}
.resultArea .resultTotal .orderOpt a{margin-right:10px;color:#0080cc;}
/*搜索结果列表区域*/
.resultArea .resultList{padding-left:30px;}
.resultArea .resultList .resultItem{margin-bottom:20px;}
.resultArea .resultList .resultItem{margin-bottom:30px;}
.resultArea .resultList .itemHead{margin-bottom:5px;color:#767676;}
.resultArea .resultList .itemHead .keyWord{color:#d90909;}
.resultArea .resultList .itemBody .keyWord{color:#d90909;}
.resultArea .resultList .itemHead a.title{font-size:16px;color:#0080cc;text-decoration:underline;}
.resultArea .resultList .itemHead .value{color:#008000;}
.resultArea .resultList .itemHead .divsion{margin:0 5px;}
.resultArea .resultList .itemHead .fileType{margin-right:10px;}
/*搜索内容主体*/
.resultArea .resultList .itemBody{margin-bottom:5px;line-height:18px;width:90%;}
.resultArea .resultList .itemFoot{color:#008000;}
.resultArea .resultList .itemFoot .info{margin-right:10px;}
.resultArea .pagination{margin-bottom:25px;padding-left:32px;}
/*相关搜索*/
.resultArea .dependSearch{margin-bottom:30px;padding-left:32px;font-size:14px;}
.resultArea .dependSearch h6{float:left;margin-right:15px;font-weight:bold;}
.resultArea .dependSearch p{margin-bottom:5px;}
.resultArea .dependSearch a{display:inline-block;margin-right:15px;text-decoration:underline;width:90px; white-space:nowrap; overflow:hidden;text-overflow:ellipsis;}
.resultArea .searchInResult{padding-left:35px;}
.resultArea .searchInResult .inResult{position:absolute;right:-190px;top:8px;font-size:14px;text-decoration:underline;}
.resultArea .searchInResult .searchButton{left:417px;}
/*历史搜索区域*/
.historyArea{float:right;margin-right:-212px;width:212px;}
.historyArea h6{margin-bottom:10px;font-weight:bold;}
.historyArea .historyList{margin-bottom:20px;}
.historyArea .historyList li{margin-bottom:5px;}
/*左侧分栏区域*/
.subfield{margin-bottom:5px;font-size:14px;font-weight:bold;padding:2px 0 2px 24px;}
.subfield:first-child{border-left:4px solid #9cc813;padding-left:20px;}
/*立即搜索样式*/
.subfieldContent .search{margin:45px 0 0 135px;width:130px;height:36px;background:url(../img/btnbg.png); font-weight:bold;border:none;border:1px solid #bfbfbf;line-height:36px;}
/*联想下拉区域*/
.inputArea .dataList{display:none;position:absolute;left:0;top:42px;*top:43px;width:550px;padding:5px 0;background:#fff;border:1px solid #bfbfbf;border-top:none;}
.inputArea .dataList li{padding:2px 15px;font-size:14px;}
.inputArea .dataList li:hover{background:#f0f0f0;color:#0080cc;font-weight:bold;}

@ -0,0 +1,67 @@
@charset "utf-8";
/*css reset*/
html, body, div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, code, del, dfn, em, img, q, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td , i{
margin:0;
padding:0;
border:0;
font-weight:inherit;
font-style:inherit;
font-size:100%;
font-family:inherit;
vertical-align:baseline;
}
body {line-height:1.5;}
table {border-collapse: collapse;border-spacing:0;}
caption, th, td ,b,strong{text-align:left;font-weight:normal;}
table, td, th {vertical-align:middle;}
blockquote:before, blockquote:after, q:before, q:after {content:"";}
blockquote, q {quotes:"" "";}
a img {border:none;}
em,cite{font-style:normal;}
body { background:#fff; font: 12px/1.5 Tahoma,'宋体';color:#000;}
h1, h2, h3, h4, h5, h6 {font-weight:normal;color:#111;}
a {text-decoration:none;cursor:pointer;}
dl, dt, dd, ol, ul, li{ list-style:none;}
/*some common class*/
.left{float:left;}
.right{float:right;}
/*clear*/
.ue-clear:after{content: ".";display:block;height:0;clear:both;visibility:hidden;}
.ue-clear{display:inline-block;}
*html .ue-clear{height:1%;}
.ue-clear{display:block;}
a{color:#0080cc;}
a:hover{color:#267A01;text-decoration:underline;}
/*logo样式*/
.logo{width:160px;height:47px;padding:0 5px;background: url(../img/logo1.png) no-repeat center center #fff;}
/*choose样式*/
.choose{float:left;margin-right:15px;white-space:nowrap;}
.choose .text{float:left;padding-left:20px;*padding-left:16px;white-space:nowrap; vertical-align:text-bottom;}
.choose input[type=radio],.choose input[type=checkbox]{position:relative;*top:-3px;float:left;margin-right:-16px;}
/*====================================
===================================*/
.pagination{font-size:14px;}
.pagination a {text-decoration: none;border: solid 1px; }
.pagination .pxofy{float:left;margin-left: 5px;height:25px;*padding-top:1px;}
.pagination a, .pagination span {display: block;float: left;height:18px;line-height:18px;padding:0 6px;margin-right: 5px;font-family:Arial, Helvetica, sans-serif !important;}
.pagination .current {cursor:default;border: solid 1px ;}
.pagination .prev, .pagination .next{*line-height:22px;}
/*分页样式*/
.pagination a{color: #032F54;border-color:#8EB2D2;}
.pagination a:hover{color:#023054;border-color:#8EB2D2;background:#B8DFFB;}
.pagination .current{color:#fff;border-color:#5c9bc4;background:#89B8D8;}
.pagination .current.prev, .pagination .current.next{color:#B9B9B9;border-color:#D3D3D3;background:#fff;}
.pagination .pxofy{color: #023054;}
#foot{height:32px;line-height:32px; text-align:center;background:#f9f9f9;border-top:1px solid #e0e0e0;color:#ababab;}

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

@ -0,0 +1,48 @@
/**
* Created by yli on 2017/4/21.
*/
var searchArr;
//定义一个search的判断浏览器有无数据存储搜索历史
if(localStorage.search){
//如果有,转换成 数组的形式存放到searchArr的数组里localStorage以字符串的形式存储所以要把它转换成数组的形式
searchArr= localStorage.search.split(",")
}else{
//如果没有则定义searchArr为一个空的数组
searchArr = [];
}
//把存储的数据显示出来作为搜索历史
MapSearchArr();
$("#btn").on("click", function(){
var val = $("#inp").val();
//点击搜索按钮时,去重
KillRepeat(val);
//去重后把数组存储到浏览器localStorage
localStorage.search = searchArr;
//然后再把搜索内容显示出来
MapSearchArr();
});
function MapSearchArr(){
var tmpHtml = "";
for (var i=0;i<searchArr.length;i++){
tmpHtml += "<span>" + searchArr[i] + "</span> "
}
$("#keyname").html(tmpHtml);
}
//去重
function KillRepeat(val){
var kill = 0;
for (var i=0;i<searchArr.length;i++){
if(val===searchArr[i]){
kill ++;
}
}
if(kill<1){
searchArr.push(val);
}
}

@ -0,0 +1,30 @@
$(document).ready(function(){
// 去除虚线框(会影响效率)
$("a,input:checkbox,input:radio,button,input:button").live('focus',function(){$(this).blur();});
});
function hideElement(currentElement, targetElement) {
if (!$.isArray(targetElement)) {
targetElement = [ targetElement ];
}
$(document).on("click.hideElement", function(e) {
var len = 0, $target = $(e.target);
for (var i = 0, length = targetElement.length; i < length; i++) {
$.each(targetElement[i], function(j, n) {
if ($target.is($(n)) || $.contains($(n)[0], $target[0])) {
len++;
}
});
}
if ($.contains(currentElement[0], $target[0])) {
len = 1;
}
if (len == 0) {
currentElement.hide();
}
});
};

File diff suppressed because it is too large Load Diff

@ -0,0 +1,193 @@
jQuery.fn.pagination = function(maxentries, opts) {
opts = jQuery.extend({
items_per_page : 10, // 每页显示多少条记录
current_page : 0, //当前页码
num_display_entries : 4, // 中间显示页码的个数
num_edge_entries : 2, // 末尾显示页码的个数
link_to : "javascript:;", //页码点击后的链接
prev_text : "上一页", //上一页的文字
next_text : "下一页", //下一页的文字
ellipse_text : "...", //页码之间的省略号
display_msg : true, // 是否显示记录信息
prev_show_always : true, //是否总是显示最前页
next_show_always : true,//是否总是显示最后页
setPageNo:false,//是否显示跳转第几页
callback : function() {
return false;
} // 回调函数
}, opts || {});
return this.each(function() {
// 总页数
function numPages() {
return Math.ceil(maxentries / opts.items_per_page);
}
/**
* 计算页码
*/
function getInterval() {
var ne_half = Math.ceil(opts.num_display_entries / 2);
var np = numPages();
var upper_limit = np - opts.num_display_entries;
var start = current_page > ne_half ? Math.max(Math.min(current_page
- ne_half, upper_limit), 0) : 0;
var end = current_page > ne_half ? Math.min(current_page + ne_half,
np) : Math.min(opts.num_display_entries, np);
return [start, end];
}
/**
* 点击事件
*/
function pageSelected(page_id, evt) {
var page_id = parseInt(page_id);
current_page = page_id;
drawLinks();
var continuePropagation = opts.callback(page_id, panel);
if (!continuePropagation) {
if (evt.stopPropagation) {
evt.stopPropagation();
} else {
evt.cancelBubble = true;
}
}
return continuePropagation;
}
/**
* 链接
*/
function drawLinks() {
panel.empty();
var interval = getInterval();
var np = numPages();
var getClickHandler = function(page_id) {
return function(evt) {
return pageSelected(page_id, evt);
}
}
var appendItem = function(page_id, appendopts) {
page_id = page_id < 0 ? 0 : (page_id < np ? page_id : np-1);
appendopts = jQuery.extend({
text : page_id+1,
classes : ""
}, appendopts || {});
if (page_id == current_page) {
var lnk = $("<span class='current'>" + (appendopts.text)
+ "</span>");
} else {
var lnk = $("<a>" + (appendopts.text) + "</a>").bind(
"click", getClickHandler(page_id)).attr('href',
opts.link_to.replace(/__id__/, page_id));
}
if (appendopts.classes) {
lnk.addClass(appendopts.classes);
}
panel.append(lnk);
}
// 上一页
if (opts.prev_text && (current_page > 0 || opts.prev_show_always)) {
appendItem(current_page - 1, {
text : opts.prev_text,
classes : "prev"
});
}
// 点点点
if (interval[0] > 0 && opts.num_edge_entries > 0) {
var end = Math.min(opts.num_edge_entries, interval[0]);
for (var i = 0; i < end; i++) {
appendItem(i);
}
if (opts.num_edge_entries < interval[0] && opts.ellipse_text) {
jQuery("<span>" + opts.ellipse_text + "</span>")
.appendTo(panel);
}
}
// 中间的页码
for (var i = interval[0]; i < interval[1]; i++) {
appendItem(i);
}
// 最后的页码
if (interval[1] < np && opts.num_edge_entries > 0) {
if (np - opts.num_edge_entries > interval[1]
&& opts.ellipse_text) {
jQuery("<span>" + opts.ellipse_text + "</span>")
.appendTo(panel);
}
var begin = Math.max(np - opts.num_edge_entries, interval[1]);
for (var i = begin; i < np; i++) {
appendItem(i);
}
}
// 下一页
if (opts.next_text
&& (current_page < np - 1 || opts.next_show_always)) {
appendItem(current_page + 1, {
text : opts.next_text,
classes : "next"
});
}
// 记录显示
if (opts.display_msg) {
if(!maxentries){
panel
.append('<div class="pxofy">暂时无数据可以显示</div>');
}else{
panel
.append('<div class="pxofy">显示第&nbsp;'
+ ((current_page * opts.items_per_page) + 1)
+ '&nbsp;条到&nbsp;'
+ (((current_page + 1) * opts.items_per_page) > maxentries
? maxentries
: ((current_page + 1) * opts.items_per_page))
+ '&nbsp;条记录,总共&nbsp;' + maxentries + '&nbsp;条</div>');
}
}
//设置跳到第几页
if(opts.setPageNo){
panel.append("<div class='goto'><span class='text'>跳转到</span><input type='text'/><span class='page'>页</span><button type='button' class='ue-button long2'>确定</button></div>");
}
}
// 当前页
var current_page = opts.current_page;
maxentries = ( maxentries < 0) ? 0 : maxentries;
opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0)
? 1
: opts.items_per_page;
var panel = jQuery(this);
this.selectPage = function(page_id) {
pageSelected(page_id);
}
this.prevPage = function() {
if (current_page > 0) {
pageSelected(current_page - 1);
return true;
} else {
return false;
}
}
this.nextPage = function() {
if (current_page < numPages() - 1) {
pageSelected(current_page + 1);
return true;
} else {
return false;
}
}
if(maxentries==0){
panel.append('<span class="current prev">'+opts.prev_text+'</span><span class="current next">'+opts.next_text+'</span><div class="pxofy">暂时无数据可以显示</div>');
}else{
drawLinks();
}
$(this).find(".goto button").live("click",function(evt){
var setPageNo = $(this).parent().find("input").val();
if(setPageNo!=null && setPageNo!=""&&setPageNo>0&&setPageNo<=numPages()){
pageSelected(setPageNo-1, evt);
}
});
});
}

@ -0,0 +1,177 @@
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
{% load static %}
<head>
<meta http-equiv="X-UA-Compatible" content="IE=emulateIE7" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>lcv-search 搜索引擎</title>
<link href="{% static 'css/style.css' %}" rel="stylesheet" type="text/css" />
<link href="{% static 'css/index.css' %}" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="container">
<div id="bd">
<div id="main">
<h1 class="title">
<div class="logo large"></div>
</h1>
<div class="nav ue-clear">
<ul class="searchList">
<li class="searchItem current" data-type="article">文章</li>
<li class="searchItem" data-type="question">问答</li>
<li class="searchItem" data-type="job">职位</li>
</ul>
</div>
<div class="inputArea">
<input type="text" class="searchInput" />
<input type="button" class="searchButton" onclick="add_search()" />
<ul class="dataList">
<li>如何学好设计</li>
<li>界面设计</li>
<li>UI设计培训要多少钱</li>
<li>设计师学习</li>
<li>哪里有好的网站</li>
</ul>
</div>
<div class="historyArea">
<p class="history">
<label>热门搜索:</label>
{% for search_words in topn_search %}
<a href="/search?q={{ search_words }}">{{ search_words }}</a>
{% endfor %}
</p>
<p class="history mysearch">
<label>我的搜索:</label>
<span class="all-search">
<a href="javascript:;">专注界面设计网站</a>
<a href="javascript:;">用户体验</a>
<a href="javascript:;">互联网</a>
<a href="javascript:;">资费套餐</a>
</span>
</p>
</div>
</div><!-- End of main -->
</div><!--End of bd-->
<div class="foot">
<div class="wrap">
<div class="copyright">Copyright &copy;uimaker.com 版权所有 E-mail:admin@uimaker.com</div>
</div>
</div>
</div>
</body>
<script type="text/javascript" src="{% static 'js/jquery.js' %}"></script>
<script type="text/javascript" src="{% static 'js/global.js' %}"></script>
<script type="text/javascript">
var suggest_url = "/suggest/"
var search_url = "/search/"
$('.searchList').on('click', '.searchItem', function(){
$('.searchList .searchItem').removeClass('current');
$(this).addClass('current');
});
function removeByValue(arr, val) {
for(var i=0; i<arr.length; i++) {
if(arr[i] == val) {
arr.splice(i, 1);
break;
}
}
}
// 搜索建议
$(function(){
$('.searchInput').bind(' input propertychange ',function(){
var searchText = $(this).val();
var tmpHtml = ""
$.ajax({
cache: false,
type: 'get',
dataType:'json',
url:suggest_url+"?s="+searchText+"&s_type="+$(".searchItem.current").attr('data-type'),
async: true,
success: function(data) {
for (var i=0;i<data.length;i++){
tmpHtml += '<li><a href="'+search_url+'?q='+data[i]+'">'+data[i]+'</a></li>'
}
$(".dataList").html("")
$(".dataList").append(tmpHtml);
if (data.length == 0){
$('.dataList').hide()
}else {
$('.dataList').show()
}
}
});
} );
})
hideElement($('.dataList'), $('.searchInput'));
</script>
<script>
var searchArr;
//定义一个search的判断浏览器有无数据存储搜索历史
if(localStorage.search){
//如果有,转换成 数组的形式存放到searchArr的数组里localStorage以字符串的形式存储所以要把它转换成数组的形式
searchArr= localStorage.search.split(",")
}else{
//如果没有则定义searchArr为一个空的数组
searchArr = [];
}
//把存储的数据显示出来作为搜索历史
MapSearchArr();
function add_search(){
var val = $(".searchInput").val();
if (val.length>=2){
//点击搜索按钮时,去重
KillRepeat(val);
//去重后把数组存储到浏览器localStorage
localStorage.search = searchArr;
//然后再把搜索内容显示出来
MapSearchArr();
}
window.location.href=search_url+'?q='+val+"&s_type="+$(".searchItem.current").attr('data-type')
}
function MapSearchArr(){
var tmpHtml = "";
var arrLen = 0
if (searchArr.length >= 5){
arrLen = 5
}else {
arrLen = searchArr.length
}
for (var i=0;i<arrLen;i++){
tmpHtml += '<a href="'+search_url+'?q='+searchArr[i]+'">'+searchArr[i]+'</a>'
}
$(".mysearch .all-search").html(tmpHtml);
}
//去重
function KillRepeat(val){
var kill = 0;
for (var i=0;i<searchArr.length;i++){
if(val===searchArr[i]){
kill ++;
}
}
if(kill<1){
searchArr.unshift(val);
}else {
removeByValue(searchArr, val)
searchArr.unshift(val)
}
}
</script>
</html>

@ -0,0 +1,273 @@
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
{% load static %}
<head>
<meta http-equiv="X-UA-Compatible" content="IE=emulateIE7" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>python-lcv-search搜索引擎</title>
<link href="{% static 'css/style.css' %}" rel="stylesheet" type="text/css" />
<link href="{% static 'css/result.css' %}" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="container">
<div id="hd" class="ue-clear">
<a href="/"><div class="logo"></div></a>
<div class="inputArea">
<input type="text" class="searchInput" value="{{ key_words }}"/>
<input type="button" class="searchButton" onclick="add_search()"/>
</div>
</div>
<div class="nav">
<ul class="searchList">
<li class="searchItem current" data-type="article">文章</li>
<li class="searchItem" data-type="question">问答</li>
<li class="searchItem" data-type="job">职位</li>
</ul>
</div>
<div id="bd" class="ue-clear">
<div id="main">
<div class="sideBar">
<div class="subfield">网站</div>
<ul class="subfieldContext">
<li>
<span class="name">伯乐在线</span>
<span class="unit">({{ jobbole_count }})</span>
</li>
<li>
<span class="name">知乎</span>
<span class="unit">(9862)</span>
</li>
<li>
<span class="name">拉勾网</span>
<span class="unit">(9862)</span>
</li>
<li class="more">
<a href="javascript:;">
<span class="text">更多</span>
<i class="moreIcon"></i>
</a>
</li>
</ul>
<div class="sideBarShowHide">
<a href="javascript:;" class="icon"></a>
</div>
</div>
<div class="resultArea">
<p class="resultTotal">
<span class="info">找到约&nbsp;<span class="totalResult">{{ total_nums }}</span>&nbsp;条结果(用时<span class="time">{{ last_seconds }}</span>秒),共约<span class="totalPage">{{ page_nums }}</span></span>
</p>
<div class="resultList">
{% for hit in all_hits %}
<div class="resultItem">
<div class="itemHead">
<a href="{{ hit.url }}" target="_blank" class="title">{% autoescape off %}{{ hit.title }}{% endautoescape %}</a>
<span class="divsion">-</span>
<span class="fileType">
<span class="label">来源:</span>
<span class="value">伯乐在线</span>
</span>
<span class="dependValue">
<span class="label">得分:</span>
<span class="value">{{ hit.score }}</span>
</span>
</div>
<div class="itemBody">
{% autoescape off %}{{ hit.content }}{% endautoescape %}
</div>
<div class="itemFoot">
<span class="info">
<label>网站:</label>
<span class="value">伯乐在线</span>
</span>
<span class="info">
<label>发布时间:</label>
<span class="value">2017-04-23</span>
</span>
</div>
</div>
{% endfor %}
</div>
<!-- 分页 -->
<div class="pagination ue-clear"></div>
<!-- 相关搜索 -->
</div>
<div class="historyArea">
<div class="hotSearch">
<h6>热门搜索</h6>
<ul class="historyList">
{% for search_word in topn_search %}
<li><a href="/search?q={{ search_word }}">{{ search_word }}</a></li>
{% endfor %}
</ul>
</div>
<div class="mySearch">
<h6>我的搜索</h6>
<ul class="historyList">
</ul>
</div>
</div>
</div><!-- End of main -->
</div><!--End of bd-->
</div>
<div id="foot">Copyright &copy;projectsedu.com 版权所有 E-mail:admin@projectsedu.com</div>
</body>
<script type="text/javascript" src="{% static 'js/jquery.js' %}"></script>
<script type="text/javascript" src="{% static 'js/global.js' %}"></script>
<script type="text/javascript" src="{% static 'js/pagination.js' %}"></script>
<script type="text/javascript">
var search_url = "{% url 'search' %}"
$('.searchList').on('click', '.searchItem', function(){
$('.searchList .searchItem').removeClass('current');
$(this).addClass('current');
});
$.each($('.subfieldContext'), function(i, item){
$(this).find('li:gt(2)').hide().end().find('li:last').show();
});
function removeByValue(arr, val) {
for(var i=0; i<arr.length; i++) {
if(arr[i] == val) {
arr.splice(i, 1);
break;
}
}
}
$('.subfieldContext .more').click(function(e){
var $more = $(this).parent('.subfieldContext').find('.more');
if($more.hasClass('show')){
if($(this).hasClass('define')){
$(this).parent('.subfieldContext').find('.more').removeClass('show').find('.text').text('自定义');
}else{
$(this).parent('.subfieldContext').find('.more').removeClass('show').find('.text').text('更多');
}
$(this).parent('.subfieldContext').find('li:gt(2)').hide().end().find('li:last').show();
}else{
$(this).parent('.subfieldContext').find('.more').addClass('show').find('.text').text('收起');
$(this).parent('.subfieldContext').find('li:gt(2)').show();
}
});
$('.sideBarShowHide a').click(function(e) {
if($('#main').hasClass('sideBarHide')){
$('#main').removeClass('sideBarHide');
$('#container').removeClass('sideBarHide');
}else{
$('#main').addClass('sideBarHide');
$('#container').addClass('sideBarHide');
}
});
var key_words = "java"
//分页
$(".pagination").pagination({{ total_nums }}, {
current_page :{{ page|add:'-1' }}, //当前页码
items_per_page :10,
display_msg :true,
callback :pageselectCallback
});
function pageselectCallback(page_id, jq) {
window.location.href=search_url+'?q='+key_words+'&p='+page_id
}
setHeight();
$(window).resize(function(){
setHeight();
});
function setHeight(){
if($('#container').outerHeight() < $(window).height()){
$('#container').height($(window).height()-33);
}
}
</script>
<script type="text/javascript">
$('.searchList').on('click', '.searchItem', function(){
$('.searchList .searchItem').removeClass('current');
$(this).addClass('current');
});
// 联想下拉显示隐藏
$('.searchInput').on('focus', function(){
$('.dataList').show()
});
// 联想下拉点击
$('.dataList').on('click', 'li', function(){
var text = $(this).text();
$('.searchInput').val(text);
$('.dataList').hide()
});
hideElement($('.dataList'), $('.searchInput'));
</script>
<script>
var searchArr;
//定义一个search的判断浏览器有无数据存储搜索历史
if(localStorage.search){
//如果有,转换成 数组的形式存放到searchArr的数组里localStorage以字符串的形式存储所以要把它转换成数组的形式
searchArr= localStorage.search.split(",")
}else{
//如果没有则定义searchArr为一个空的数组
searchArr = [];
}
//把存储的数据显示出来作为搜索历史
MapSearchArr();
function add_search(){
var val = $(".searchInput").val();
if (val.length>=2){
//点击搜索按钮时,去重
KillRepeat(val);
//去重后把数组存储到浏览器localStorage
localStorage.search = searchArr;
//然后再把搜索内容显示出来
MapSearchArr();
}
window.location.href=search_url+'?q='+val+"&s_type="+$(".searchItem.current").attr('data-type')
}
function MapSearchArr(){
var tmpHtml = "";
var arrLen = 0
if (searchArr.length > 6){
arrLen = 6
}else {
arrLen = searchArr.length
}
for (var i=0;i<arrLen;i++){
tmpHtml += '<li><a href="/search?q='+searchArr[i]+'">'+searchArr[i]+'</a></li>'
}
$(".mySearch .historyList").append(tmpHtml);
}
//去重
function KillRepeat(val){
var kill = 0;
for (var i=0;i<searchArr.length;i++){
if(val===searchArr[i]){
kill ++;
}
}
if(kill<1){
searchArr.unshift(val);
}else {
removeByValue(searchArr, val)
searchArr.unshift(val)
}
}
</script>
</html>
Loading…
Cancel
Save