Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

jquery - JavaScript- find text within a page and jump to location in page

I have a webpage with a large list of records (say 250+ rows of data in a table) and want to be able to just visit the page, immediately start typing, and have it jump me to the first row that matches the text I have typed.

Ideally, if I then continued to type more characters so the first match doesn't match anymore, it could then continue to respond to my input and jump me to the new match.

I've tried with window.find() but haven't had much success... can anyone reccomend a working solution?

I'm essentially looking for the equivalent to hitting 'CTRL-F' on my keyboard... except without the need to hit CTRL-F to make it happen.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think the tricky part of this is actually the accepting of user input intelligently. Therefore, I'd say the best thing to do is to pass off your searching to an autocomplete-type plugin. Once the page is ready, you pass the focus to an input text box, and then let the plugin do its magic as you search...

For example, you could use the quicksearch plugin.

Then given a table of data and an input like this:

<input id="searcher" type="text" name="searcher">

You could have a ready function that looks like this:

$('#searcher').quicksearch('table tbody tr', {
    'delay': 100,
    'bind': 'keyup keydown',
    'show': function() {
        if ($('#searcher').val() === '') {
            return;
        }
        $(this).addClass('show');
    },
    'onAfter': function() {
        if ($('#searcher').val() === '') {
            return;
        }
        if ($('.show:first').length > 0){
            $('html,body').scrollTop($('.show:first').offset().top);
        }
    },
    'hide': function() {
        $(this).removeClass('show');
    },
    'prepareQuery': function(val) {
        return new RegExp(val, "i");
    },
    'testQuery': function(query, txt, _row) {
        return query.test(txt);
    }
});

$('#searcher').focus();

Try it out here: http://jsfiddle.net/ZLhAd/369/

EDIT: other answer/comment added in to make the input fixed and stop the scollbar jumping around so ridiculously.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...