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

后端 未结 2 1341
南旧
南旧 2020-12-10 03:49

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

相关标签:
2条回答
  • 2020-12-10 03:59

    OK, here's a different take, using keypress directly:

    http://jsfiddle.net/ryleyb/VFVZL/1/

    Basically, bind keypress and use that:

    $('body').keypress(function(e) {
        $('#typed').append(String.fromCharCode(e.which));
        if (!findString($('#typed').text())) {
            $('#typed').text('');
        }
    });
    

    findString is just some vaguely cross browser page string finder. See the fiddle for details.

    0 讨论(0)
  • 2020-12-10 04:19

    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.

    0 讨论(0)
提交回复
热议问题