Lazy loading SELECT element options w/ jquerymobil

2019-04-12 13:23发布

I have a SELECT element on one of my jQuery Mobile pages that has a lot of possible values. Obviously loading all of the options on page load raises performance issues on mobile handsets. What is a good way to load items "on demand"?

An example of what I need is how the Android market loads app lists: x number of items load initially, then x more items load once you've scrolled to the bottom of the options, then x more...and so on).

I'm using C#/ASP.NET (Razor syntax) to implement jQuery Mobile.

1条回答
太酷不给撩
2楼-- · 2019-04-12 14:05

Here's my solution. The idea is to implement a kind of Twitter-like pagination and that you should render some choices from the beginning.

<div data-role="page">

    <div data-role="header">
        <h1>Page Title</h1>
    </div><!-- /header -->

    <div data-role="content">   
        <p>Page content goes here.</p>

        <div data-role="fieldcontain">
            <label for="select-choice-1" class="select">Choose shipping method:</label>
            <select name="select-choice-1" id="select-choice-1">
                <option value="standard">Standard: 7 day</option>
                <option value="rush">Rush: 3 days</option>
                <option value="express">Express: next day</option>
                <option value="overnight">Overnight</option>
                <option value="-1">More...</option>
            </select>
        </div>

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

    <div data-role="footer">
        <h4>Page Footer</h4>
    </div><!-- /footer -->
</div><!-- /page -->

Then hook some handlers to the More option

<script type="text/javascript">
    $(document).bind("pageshow", function(){
        bindMore();
    });

    function bindMore(){
        // The rendered select menu will add "-menu" to the select id
        $("#select-choice-1-menu li").last().click(function(e){handleMore(this, e)});
    }

    function handleMore(source, e){

        e.stopPropagation();

        var $this = $(source);

        $this.unbind();

        $this.find("a").text("Loading...");

        // Get more results
        $.ajax({
            url: "test.js",
            dataType: "script",
            success: function(data){
                $(eval(data)).each(function(){

                    // Add options to underlaying select
                    $("#select-choice-1 option").last()
                        .before($("<option></option>")
                        .attr("value", this.value)
                        .text(this.text)); 

                });

                // Refresh the selectmenu
                $('#select-choice-1').selectmenu('refresh');

                // Rebind the More button
                bindMore();

            }
        });
    }
</script>

Test.js contains this:

[
        {"value": "1", "text": "1"},
        {"value": "2", "text": "2"},
        {"value": "3", "text": "3"}
]
查看更多
登录 后发表回答