jquery移动自动完成功能

时间:2013-12-16 19:23:14

标签: jquery jquery-mobile

此示例实现了jquery移动自动完成功能。 它有效,但我想就其效率和最佳实践提出意见。

查看代码中的问题,特别是选择器的使用和某些功能的使用。

<!DOCTYPE html>
<html>
    <head>
    <meta charset="utf-8"/>

    <!-- standard Jquery/jQuery Mobile Libraries -->
    <script src="../jquery.mobile/jquery.js"></script>
    <script src="../jquery.mobile/jquery.mobile.js"></script>
    <link href="../jquery.mobile/jquery.mobile.css" rel="stylesheet"/>

    <script>

        // show auto-complete values 
        $( document ).on( "pageinit", "#myPage", function() {
            $( ".autocomplete" ).on( "listviewbeforefilter", function ( e, data ) {
                var $ul = $( this ),
                    $input = $( data.input ),
                    value = $input.val(),
                    html = "";
                $ul.html( "" );

                // hard code some values... to replace with AJAX call
                var response = ['1111','1112','1113','1114','2116','2117','2119'];

                // on third character, trigger the drop-down
                if ( value && value.length > 2 ) {
                    $('.autocomplete').show();  // IS THIS BEST WAY?
                    $ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading' ></span></div></li>" );
                    $ul.listview( "refresh" );
                    $.each(response, function( index, val ) {
                            html += "<li>" + val + "</li>";
                        $ul.html( html );
                        $ul.listview( "refresh" );
                        $ul.trigger( "updatelayout");           // DO I NEED THIS?
                    });
                }
            })
        });     

        // click to select value of auto-complete
        $( document).on( "click", ".autocomplete li", function() {          
            var selectedItem = $(this).html();
            $(this).parent().parent().find('input').val(selectedItem);  // IS THIS MOST EFFICIENT WAY?
            $('.autocomplete').hide();      // IS THIS BEST WAY?
        });

    </script>
    <style>
        .ui-listview-filter-inset {
            margin-top: 0;
        }
    </style>
</head>

<body>
<div data-role="page" id="myPage">

    <div data-role="header" data-theme="f">     
        <a href="../" data-icon="home" data-iconpos="notext" data-ajax="false">Home</a>
    </div><!-- /header -->

    <div data-role="content">

    <br/>
    <p>Try to find parts starting with 111,211 and maybe 311...</p>
            <div data-demo-html="true" data-demo-js="true" data-demo-css="true">
                <ul class="autocomplete" data-role="listview" data-inset="true" data-filter="true" data-filter-placeholder="" data-filter-theme="d"></ul>
            </div><!--/demo-html -->

    </div><!-- /content -->


</div><!-- /page -->

</body>
</html>

0 个答案:

没有答案