簡體   English   中英

如何使用jquery中的下一個和上一個功能從頁面搜索文本

[英]How to search text from page with next and previous functionality in jquery

我正在頁面上實現文本搜索功能。我找到了很多鏈接。但我需要更多的功能。

這是一個很好的例子http://jsfiddle.net/z7fjW/137/

function searchAndHighlight(searchTerm, selector) {
    if(searchTerm) {
        //var wholeWordOnly = new RegExp("\\g"+searchTerm+"\\g","ig"); //matches whole word only
        //var anyCharacter = new RegExp("\\g["+searchTerm+"]\\g","ig"); //matches any word with any of search chars characters
        var selector = selector || "body";                             //use body as selector if none provided
        var searchTermRegEx = new RegExp(searchTerm,"ig");
        var matches = $(selector).text().match(searchTermRegEx);
        if(matches) {
            $('.highlighted').removeClass('highlighted');     //Remove old search highlights
                $(selector).html($(selector).html()
                    .replace(searchTermRegEx, "<span class='highlighted'>"+searchTerm+"</span>"));
            if($('.highlighted:first').length) {             //if match found, scroll to where the first one appears
                $(window).scrollTop($('.highlighted:first').position().top);
            }
            return true;
        }
    }
    return false;
}

但我需要它只搜索第一個單詞(現在第一個)然后使用下一個它進入下一個(轉到下一個位置)。然后前一個(轉到上一個位置).as在記事本中? 查詢中這可能嗎?

而不是直接highligt他們添加類“匹配”並使用它

$(selector).html($(selector).html()
                    .replace(searchTermRegEx, "<span class='match'>"+searchTerm+"</span>"));

//to highlighted specific index 
$('.match:first').addClass('highlighted');

//to work with index you need you var matches to know what indexes exist
$('.match').eq(3).addClass('highlighted');

演示

我查看了http://jsfiddle.net/ruddog2003/z7fjW/141/ ,這是一個很好的起點。 我稍微修改了邏輯以允許下一個和前一個,並且更加健壯。 它並不完美,但這里遵循我的AJAX格式的代碼

HTML

> <div data-role="content">
>     <div id="fulltext-search"> 
>         <input type="text" name="search-input" value="" placeholder="Type text here..."/>
>         <input type="button" name="search-action" value="Search"/>
>         <button id="searchPrevious"> &lt;&lt; </button>
>         <button id="searchNext"> &gt;&gt; </button>
>     </div>
> </div>

CSS

#document_fulltext [data-role="content"] #fulltext-search {
    width: 100%;
    text-align: center;
    position: fixed;
    top: 0px;
    background-color: rgba(255,255,255, 0.8);
    z-index: 10000;
    border-bottom: 1px solid #000;
}
.highlighted {
    color: white;
    background-color: rgba(255,20,0,0.5);

    padding: 3px;
    border: 1px solid red;
    -moz-border-radius: 15px;
    border-radius: 15px;
}

JAVASCRIPT EVENT

$(document).ready(function( ) {
    loadFulltext();
    //Load full text into the designated div
    function loadFulltext(searchString){
        //reset
        $("#fulltext").html('');
        filePath = 'http://localhost/income_tax_act_58_of_1962.html';
        $.ajax({
            url: filePath,
            beforeSend: function( xhr ) {
                xhr.overrideMimeType( "text/html; charset=UTF-8;" );
            },
            cache: false,
            success: function(html){
                $("#fulltext").html(html);
                // if search string was defined, perform a search
                if ((searchString != undefined) && (searchString != '') && (searchString != null)){
                    if(!searchAndHighlight(searchString, '#fulltext')) {
                        alert("No results found");
                    }
                }
            },
            fail: function(){
                alert('FAIL');
            }
        });
    }
    /* ------------------------------ CLICK - REFRESH DOCUMENTS LIST --- */
    $(document).on('click', 'input[name="search-action"]', function ( event ){
        // load fresh copy of full text into the div and perform a search once it is successfully completed
        loadFulltext($('input[name="search-input"]').val());
    });
});

JAVASCRIPT FUNCTION

function searchAndHighlight(searchTerm, selector) {
    if(searchTerm) {
        $('.highlighted').removeClass('highlighted');     //Remove old search highlights
        $('.match').removeClass('match');     //Remove old matches

        //var wholeWordOnly = new RegExp("\\g"+searchTerm+"\\g","ig"); //matches whole word only
        //var anyCharacter = new RegExp("\\g["+searchTerm+"]\\g","ig"); //matches any word with any of search chars characters
        var selector = selector || "body";                             //use body as selector if none provided
        var searchTermRegEx = new RegExp(searchTerm,"ig");
        var matches = $(selector).text().match(searchTermRegEx);
        // count amount of matches found
        if(matches) {
            alert('['+matches.length+'] matches found');
            // replace new matches
            $(selector).html($(selector).html().replace(searchTermRegEx, "<span class='match'>"+searchTerm+"</span>"));
            // add highligt to first matched class
            $('.match:first').addClass('highlighted');

            // keep track of next and previous. Start at one because on SEARCH the forst one was already highlightes
            var matchIndex = 1;
            // look out for user click on NEXT
            $('#searchNext').on('click', function() {
                //Re-set match index to create a wrap effect if the amount if next clicks exceeds the amount of matches found
                if (matchIndex >= matches.length){
                    matchIndex = 0;
                }

                var currentMatch = $('.match');
                currentMatch.removeClass('highlighted');

                var nextMatch = $('.match').eq(matchIndex);
                matchIndex += 1;
                nextMatch.addClass('highlighted');

                // scroll to the top of the next found instance -n to allow easy viewing
                $(window).scrollTop(nextMatch.offset().top-30);
            });
            // look out for user click on PREVIOUS
            $('#searchPrevious').on('click', function() {
                //Re-set match index to create a wrap effect if the amount if next clicks exceeds the amount of matches found
                if (matchIndex < 0){
                    matchIndex = matches.length-1;
                }

                var currentMatch = $('.match');
                currentMatch.removeClass('highlighted');

                var previousMatch = $('.match').eq(matchIndex-2);
                matchIndex -= 1;
                previousMatch.addClass('highlighted');

                // scroll to the top of the next found instance -n to allow easy viewing
                $(window).scrollTop(previousMatch.offset().top-30);
            });

            // if match found, scroll to where the first one appears
            if($('.highlighted:first').length) {
                $(window).scrollTop($('.highlighted:first').position().top);
            }
            return true;
        }
    }
    return false;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM