jQuery 搜索關鍵字,並突出顯示

css: .tuc  { color:red; }




        //模糊查詢調用此方法即可
        function mh_Search() {
            $(".search_mh").keyup(function () {
                var mh = $(this).val();
                console.log(mh);
                //每次恢復原樣
                $(".sInfo td b").replaceWith($(".sInfo td b").html());  
                
                if (mh.trim() != "" && mh != "undefined") {
                    setCss(mh);


                } else {
                    clearSelection();
                }



            });
        }


        function setCss(searchText) {
            clearSearch();//先清空 
            var regExp = new RegExp(searchText, 'g');//正則篩選; 
            $('.sInfo td').each(function ()//遍歷獲取; 
            {
                var html = $(this).html();
                var newHtml = html.replace(regExp, '<span class="tuc  ">' + searchText + '</span>');//設置 

                $(this).html(newHtml);//替換; 
            });
        }
        //清除高亮顯示效果
        function clearSearch() {
            $('.sInfo td').each(function ()//遍歷 
            {
                $(this).find('.tuc ').each(function ()//找到所有tuc屬性的元素; 
                {
                    $(this).replaceWith($(this).html());//將他們的屬性去掉; 
                });
            });
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章