码迷,mamicode.com
首页 > Web开发 > 详细

JQuery 在网页中查询

时间:2015-05-26 17:57:12      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

最近遇到客户的一个需求,要在网页中添加一个Search 功能,其实对于网页的搜索,Ctrl+F,真的是非常足够了,但是客户的需求,不得不做,这里就做了个关于Jquery Search function的简单研究。欢饮提出不同解决方法。

 

1,使用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>
View Code

在浏览器中可以看到。

 

技术分享

这是个非常简单的例子,在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;
        };
View Code

在包含上述代码后,再在浏览器中查看效果;

技术分享

可以看出,这里已经不区分大小写了。

如果我们想,在搜索输入框中,输入关键字,然后文本高亮显示,使用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>
View Code

再看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‘);
 });
View Code

查看效果;

技术分享

 

2,使用IndexOf函数。

其实,这是非常简单的方法。只是使用索引去查看有没有具体的值,如果有,表示搜索的关键字存在。

很多时候,在我们搜索后,如果想关键字高亮显示,这可以使用简单的插件。查看完整代码;

技术分享
<!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) {
                    var newHtml = "";
                    //清空查询结果
                    $(#searchResult).html(‘‘);
                    var itemIndex = 0;
                    $(.Faq > li).each(function () {

                        var $this = $(this).clone();
                        //用indexOf,查看是否包含关键字
                        if ($this.html().toLowerCase().indexOf(item.toLowerCase()) >= 0) {

                            $this.highlight(item);

                            //重新组建索引
                            $this.find(i).text(itemIndex++);
                            newHtml += "<li> " + $this.html() + "</li>";
                        }
                        if (newHtml.length == 0) {
                            newHtml = "<h1>0 results </h1>";
                            newHtml += "<br />Your search returned no matches.";
                        }
                    });
                    $(#searchResult).append(newHtml);
                    $(.Faq).hide();
                }
            });


        });

        jQuery.expr[":"].Contains = jQuery.expr.createPseudo(function (arg) {
            return function (elem) {
                return jQuery(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>
View Code

 

这里是网页显示截图;

技术分享

从上图中可以看到,有一个搜索框,一个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.

 最后看看搜索结果,高亮显示关键字;

技术分享

3,如果从数据库查询,这个需要用到模糊查询,like ‘%keyword%’.

然后通过DataTable 绑定到显示控件,或者用Ajax 绑定到UI.这里就不列例子了。

 

欢迎提出不同解决方案,期待更好的解决方案。

 

JQuery 在网页中查询

标签:

原文地址:http://www.cnblogs.com/lideng/p/4530856.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!