最近遇到客户的一个需求,要在网页中添加一个Search 功能,其实对于网页的搜索,Ctrl+F,真的是非常足够了,但是客户的需求,不得不做,这里就做了个关于Jquery Search function的简单研究。欢饮提出不同解决方法。
使用Contains函数。
描述: 选择所有包含指定文本的元素。
jQuery( ":contains(text)" )
text: 用来查找的一个文本字符串。这是区分大小写的。
这里是官方链接:http://www.jquery123.com/api/contains-selector/
这里看个简单的demo.
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="Script/jquery-1.11.2.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("div:contains('John')").css("text-decoration", "underline"); }); </script> </head> <body> <form id="form1" runat="server"> <div>John Resig</div> <div>George Martin</div> <div>Malcom John Sinclair</div> <div>J. Ohn</div> <div>john mohan</div> </form> </body> </html>
在浏览器中可以看到。
这是个非常简单的例子,在div中,只要包含了John,就添加下划线,这里区分大小写的。
如果我们不想区分大小写,这里需要用到Jquery 扩展;
可以查看这个链接:https://css-tricks.com/snippets/jquery/make-jquery-contains-case-insensitive/
jQuery.expr[':'].Contains = function (a, i, m) { return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0; };
在包含上述代码后,再在浏览器中查看效果;
可以看出,这里已经不区分大小写了。
如果我们想,在搜索输入框中,输入关键字,然后文本高亮显示,使用Contains函数,看这个demo。
这里是链接:http://jsfiddle.net/bipen/dyfRa/
这里是Html 代码;
Type Something: <input id="textBoxID" /> <table id="table" border=1> <tr style="display:table-row"> <th class="Name">NAME</th> <th class="Score">SCORE</th> <th class="Email">EMAIL</th> </tr> <tr> <!--tabledata--> <td >jQuery</td> <td >39</td> <td >test@gmail.com</td> </tr> <tr> <td >Javascript</td> <td >34</td> <td >abc@gmail.com</td> </tr> </table>
再看Jquery 代码:
$.extend($.expr[":"], { "containsIN": function(elem, i, match, array) { return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0; } }); $('#textBoxID').keyup(function(){ $('td').css("background-color",''); var value= $(this).val(); $('td:containsIN("'+value+'")').css("background-color",'red'); });
查看效果;
项目实践:
在实际的应用中,一般都要求会比较高,比如优先匹配全文(full text match)。然后匹配数目多的(split word by word)。根据匹配数目的多少排序。
排序需要用到数组的Sort函数,看个简单例子
Example
Sort numbers in an array in ascending order:
var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a-b});
The result of points will be:
在我们搜索后,如果想关键字高亮显示,这可以使用简单的插件。查看完整代码;
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SearchDemo.aspx.cs" Inherits="Jquery_Programming.SearchDemo" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="Script/jquery-1.11.2.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { // $("div:Contains('John')").css("text-decoration", "underline"); //press enter key to trigger click button $('#txtSearch').keypress(function (event) { if (event.keyCode == 13) { $('#btnSearch').trigger('click'); event.stopPropagation(); return false; } }); $('#btnSearch').click(function () { var item = $('#txtSearch').val(); if (item.length > 0) { //清空查询结果 $('#searchResult').html(''); var itemIndex = 0; var newHtml = ""; //Use a regular expression (s matches spaces, tabs, new lines, etc.) var itemArr = item.split(/s+/); var newItemArr = []; var maxCount = 0; var fullMaxCount = 100; $('.Faq > li').each(function (index) { var $this = $(this).clone(); //first time the full text match if ($this.is(":contains('" + item + "')")) { $this.highlight(item); var p = {}; p.index = index; p.keyCount = fullMaxCount; p.refThis = $this; p.refText = $this.text(); newItemArr[index] = p; return; //jump the belowing code. } //then match word by word for (var i = 0, len = itemArr.length; i < len; i++) { // if ($this.text().toLowerCase().split(/s+/).indexOf(itemArr[i].toLowerCase()) >= 0) { if ($this.is(":contains('" + itemArr[i] + "')")) { if (newItemArr[index] && newItemArr[index] != null) { newItemArr[index].keyCount++; } else { $this.highlight(itemArr[i]); var p = {}; p.index = index; p.keyCount = 1; p.refThis = $this; p.refText = $this.text(); newItemArr[index] = p; } } } }); if (newItemArr.length > 0) { newItemArr.sort(function (a, b) { return b.keyCount - a.keyCount; }); var icount = Math.floor(maxCount / 2); $.each(newItemArr, function (i, obj) { if (obj != undefined) { obj.refThis.find('i').text(itemIndex++); newHtml += "<li> " + obj.refThis.html() + "</li>"; } }); } if (newHtml.length == 0) { newHtml = "<h1>0 results </h1>"; newHtml += "<br />Your search returned no matches."; } $('#searchResult').append(newHtml); $('.Faq').hide(); } }); }); $.expr[":"].contains = $.expr.createPseudo(function (arg) { return function (elem) { return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0; }; }); jQuery.fn.highlight = function (pat) { function innerHighlight(node, pat) { var skip = 0; if (node.nodeType == 3) { var pos = node.data.toUpperCase().indexOf(pat); if (pos >= 0) { var spannode = document.createElement('span'); spannode.className = 'highlight'; var middlebit = node.splitText(pos); var endbit = middlebit.splitText(pat.length); var middleclone = middlebit.cloneNode(true); spannode.appendChild(middleclone); middlebit.parentNode.replaceChild(spannode, middlebit); skip = 1; } } else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) { for (var i = 0; i < node.childNodes.length; ++i) { i += innerHighlight(node.childNodes[i], pat); } } return skip; } return this.each(function () { innerHighlight(this, pat.toUpperCase()); }); }; jQuery.fn.removeHighlight = function () { function newNormalize(node) { for (var i = 0, children = node.childNodes, nodeCount = children.length; i < nodeCount; i++) { var child = children[i]; if (child.nodeType == 1) { newNormalize(child); continue; } if (child.nodeType != 3) { continue; } var next = child.nextSibling; if (next == null || next.nodeType != 3) { continue; } var combined_text = child.nodeValue + next.nodeValue; new_node = node.ownerDocument.createTextNode(combined_text); node.insertBefore(new_node, child); node.removeChild(child); node.removeChild(next); i--; nodeCount--; } } return this.find("span.highlight").each(function () { var thisParent = this.parentNode; thisParent.replaceChild(this.firstChild, this); newNormalize(thisParent); }).end(); }; </script> <style type="text/css"> li { line-height: 30px; font-family: Arial; } #txtSearch { width: 200px; } i { font-size: 14px; font-weight: bold; margin: 10px; } ul { list-style-type: none; } .highlight { background-color: #fff34d; -moz-border-radius: 5px; /* FF1+ */ -webkit-border-radius: 5px; /* Saf3-4 */ border-radius: 5px; /* Opera 10.5, IE 9, Saf5, Chrome */ -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* FF3.5+ */ -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* Saf3.0+, Chrome */ box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* Opera 10.5+, IE 9.0 */ } .highlight { padding:1px 4px; margin:0 -4px; } </style> </head> <body> <form id="form1" runat="server"> <div> Search Here:<input id="txtSearch" placeholder="Please input key words to search" /> <input type="button" id="btnSearch" value="Search" /></div> <ul id="searchResult"> </ul> <ul class="Faq"> <li><i>1</i>Question bans do not affect other privileges, such as commenting or voting, and there is no indication to the rest of the community that a particular user has been banned.</li> <li><i>2</i>The ban will be lifted automatically by the system when it determines that your positive contributions outweigh those questions which were poorly received.</li> <li><i>3</i>The only way to end a posting block is to positively contribute to the site; automatic bans never expire or "time out".</li> <li><i>4</i>If you see a similar message when trying to post an answer, please see our guidance on what to do about answer bans.</li> <li><i>5</i>Reading your question out loud to yourself can help you understand what it sounds like to others. Here are some additional tips for writing good, useful questions:</li> </ul> </form> </body> </html>
这里是网页显示截图;
查看搜索效果:
从上图中可以看到,有一个搜索框,一个Search的按钮,一些文本内容,当我们输入关键词,可以按enter 键或者点击Search button.
当如果有搜索结果时,我们隐藏以前的内容,只显示搜索结果。
为什么直接在输入框中按enter键可以工作呢,看这里代码;
$('#txtSearch').keypress(function (event) { if (event.keyCode === 13) { $('#btnSearch').trigger('click'); event.stopPropagation(); return false; } });
如果keyCode ===13, 我们就trigger the button's click method.
如果从数据库查询,这个需要用到Freetext in mssql.
然后通过DataTable 绑定到显示控件,或者用Ajax 绑定到UI.这里就不列例子了。
欢迎提出不同解决方案,期待更好的解决方案。