welcome to xlongwei.com

欢迎大家一起学习、交流、分享


QQ:9167702333 邮箱:admin@xlongwei.com

添加百度站内搜索框


分类 OurJS   关键字 分享   标签 web   jquery   发布 hongwei  1428221564683
注意 转载须保留原文链接,译文链接,作者译者等信息。  
先注册百度站长平台账户,进入“其他工具”-》“站内搜索”,添加搜索框即可。


查看代码,写入到header.part,
<li class="dropdown">
<script type="text/javascript">(function(){document.write(unescape('%3Cdiv id="bdcs"%3E%3C/div%3E'));var bdcs = document.createElement('script');bdcs.type = 'text/javascript';bdcs.async = true;bdcs.src = 'http://znsv.baidu.com/customer_search/api/js?sid=7334741412480874390' + '&plate_url=' + encodeURIComponent(window.location.href) + '&t=' + Math.ceil(new Date()/3600000);var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(bdcs, s);})();</script>
</li>

编辑样式


最终效果,


切换至https之后搜索框出不来了……

给OurJS加上简单搜索功能

<li class="dropdown">
<input id="q" placeholder="搜索" style="width:100px;height:27px;margin-top:5px;color:#aaa;background:transparent;border:1px solid #ccc;" onkeypress="search(this, event)">
<script>function search(q,e){ if(q.value && (e.keyCode==10 || e.keyCode==13)){ location.href = "/home/?q="+q.value; } }</script>
</li>
搜索请求地址为:https://www.xlongwei.com/home/?q=caifuxiang

后台处理代码
var showListHandler = function(req, res, url) {
var params = webSvr.parseUrl('/:template/:category/:pagerNumber', url || req.url)
, query = require("url").parse(url || req.url, true).query //参数有url,所以直接用require("url")
, category = params.category || ''
, title = categories[category]
, template = params.template || 'home'
, pageNumber = parseInt(params.pagerNumber) || 0

// Category and title doesn't exist redirect to home page
if (!title) {
return res.redirect('/')
}

var articles = (Articles.categoryArticles[category] || [])
if(query.q) {
var q = query.q.toLowerCase()
var filterArticles = []
for(idx = 0, len = articles.length; idx < len; idx++){
var article = articles[idx] //简单实用indexOf查找,百度站内搜索不给力,但搜索又比较重要
if(article.title.toLowerCase().indexOf(q)>-1 || (article.content && article.content.toLowerCase().indexOf(q)>-1)){
filterArticles.push(article)
}
}
articles = filterArticles
}else{ //搜索和分页有冲突,所以搜索时一次性列出所有文章,分页是ajax请求会遗漏参数q
articles = articles.slice(pageNumber * pageSize, (pageNumber + 1) * pageSize)
}