用于AJAX Live搜索的箭头键和鼠标导航

时间:2016-09-12 18:35:13

标签: php jquery html css ajax

我在网页中使用以下代码进行自动填充功能。问题是我无法使用鼠标指针浏览建议。但是,如果在列表项刷新后按下向上/向下键,鼠标指针导航工作正常。

  1. 您能否建议更改代码以使鼠标指针和键盘导航像html选项中的导航一样工作?
  2. 如何使用上/下键改进建议列表的滚动?
  3. HTML:

    <div class="field-wrap">
    
    <input type="text" id="college"  placeholder="College Name" required autocomplete="off"/>
    <ul id="college_list"></ul>
    
    </div>
    

    CSS:

    .field-wrap ul {
        width: 93%;
        margin-top: 1px;
        border: 1px solid #3498DB;
        position: absolute;
        z-index: 9;
        background: #0F0F0F;
        list-style: none;
        max-height: 100px;
        overflow-y:auto;
    }
    
    .field-wrap ul li {
        padding: 2px;
        border: solid grey;
        border-width: 0 0 2px 0;
    }
    
    
    #college_list {
        display: none;
    }
    
    .selected {
        background: #2980B9;
    }
    

    使用Javascript:

    // livesearch : this function will be executed every time we change the text
    function livesearch() {
        var min_length = 1; // min caracters to display the autocomplete
        var keyword = $.trim($('#college').val());
        if (keyword.length >= min_length) {
            $.ajax({
                url: 'livesearch.php',
                type: 'POST',
                data: {keyword:keyword},
                success:function(data){
                    $('#college_list').show();
                    $('#college_list').html(data);
                }   
            });
    
        } else {
            $('#college_list').hide();
        }
    }
    
    // set_item : this function will be executed when we select an item
    function set_item(item) {
    
        // change input value
        $('#college').val(item);
    
        // after selecting an item, update list item and hide proposition list 
        var min_length = 1; // min caracters to display the autocomplete
        var keyword = $('#college').val();
            if (keyword.length >= min_length) {
                $.ajax({
                    url: 'livesearch.php',
                    type: 'POST',
                    data: {keyword:keyword},
                    success:function(data){
                        $('#college_list').hide();
                        $('#college_list').html(data);
                    }
                });
            }
    
    }
    
    // Display or hide list based on focus in search box
    
    $('#college').focus(function() {
    
        livesearch();
    
        $(document).bind('focusin.college click.college',function(e) {
            if ($(e.target).closest('#college, #college').length) return;
            $(document).unbind('#college');
            $('#college_list').fadeOut('medium');
        });
    
    });
    
    
    // Disable default behaviour of form submit when enter is pressed for livesearch text box
    
    $('#college').bind('keypress keydown keyup', function(e){
           if(e.keyCode == 13 ) { e.preventDefault(); }
    });
    
    
    // Livesearch list or navigate and select a list item based on keyup events 
    
    $('#college').keyup(function(e)
    {   
    
        var $listItems = $('.field-wrap li');
        var key = e.keyCode,
            $selected = $listItems.filter('.selected'),
            $current;
    
    
    // Search text pattern in database if key pressed is not up/down/enter 
    
        if ( key != 40 && key != 38 && key != 13 ) livesearch();
    
    
        $listItems.removeClass('selected');
    
    // navigate or select list item based on up/down/enter key pressed if list is visible
    
        if($('#college_list').is(':visible')) {
    
            var menu = $('#college_list');
            var height = $selected.outerHeight(); //Height of <li>
            var top = menu.scrollTop(); //Current top of scroll window
            var menuHeight = menu[0].scrollHeight; //Full height of <ul>
    
            if ( key == 40 ) // Down key
            {
                if ( ! $selected.length || $selected.is(':last-child') ) {
                    $current = $listItems.eq(0);
                    menu.scrollTop(0);
                }
                else {
                    $current = $selected.next();
                    menu.scrollTop(top + height);
                }   
    
                $current.addClass('selected');          
            }
    
            if ( key == 38 ) // Up key
            {
                if ( ! $selected.length || $selected.is(':first-child') ) {
                    $current = $listItems.last();   
                    menu.scrollTop(menuHeight + height);
                }
                else {
                    $current = $selected.prev();
                    menu.scrollTop(top - height);
                }
                $current.addClass('selected');
            }
    
            if ( key == 13 ) // Enter key
            {    
            $current = $selected;
    
            // If selected text in list is not blank change the text in search box else hide list and retain entered text in search box
    
                if($current.addClass('selected').text()!='') {
                    set_item( $current.addClass('selected').text() );
                }
                else {
                    $('#college_list').fadeOut('medium');
                }
            }
    
        }
    
            $('#college_list li').mousemove(function() {
                $('.field-wrap li').removeClass('selected');
                $(this).addClass('selected');
            });
    });
    

    Livesearch.php:

    <?php
    // PDO connect *********
    function connect() {
        return new PDO('mysql:host=localhost;dbname=expertreaders', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
    }
    
    $pdo = connect();
    $keyword = '%'.$_POST['keyword'].'%';
    $sql = "SELECT * FROM colleges WHERE college_name LIKE (:keyword) ORDER BY college_name ASC";
    $query = $pdo->prepare($sql);
    $query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
    $query->execute();
    $list = $query->fetchAll();
    foreach ($list as $rs) {
        // put in bold the written text
        $college_name = preg_replace('/' . preg_quote($_POST['keyword'], "/") . '/i', "<b><font color=green>\$0</font></b>", $rs['college_name']);
        // add new option
        echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['college_name']).'\')">'.$college_name.'</li>';
    }
    
    ?>
    

    提前致谢。

1 个答案:

答案 0 :(得分:1)

按键操作后鼠标导航工作,因为您在mousemove事件中定义了keyup事件处理程序。对于像这样动态创建的html内容,总是使用$(document).bind$(document).on之类的函数作为事件处理程序。 您的代码中有重复的事件处理程序。这是必要的吗? 例如:

$('#college').bind('keypress keydown keyup', function(e){
       if(e.keyCode == 13 ) { e.preventDefault(); }
});


// Livesearch list or navigate and select a list item based on keyup events 

$('#college').keyup(function(e)
{   

    var $listItems = $('.field-wrap li');
    var key = e.keyCode,
        $selected = $listItems.filter('.selected'),
        $current;

使用单个处理程序并应用条件。 喜欢

if(e.keyCode == 13 ) { //do some stuff 
}
else {
//Do something else
}

试试我的回答。如果你有什么不对,请原谅我