开发者

jQuery Mobile - Going directly to hash URL causes dynamic elements to fail

I'm running into an issue where dynamic elements on a page are updated on "pageshow". This works great if the user goes directly to the url or navigates to it from somewhere else in the site. The problem is if I go directly to that page, or refresh it (eg: mydomain.com/#somepage.html) it fails and I get the error:

Uncaught cannot call methods on selectmenu prior to initialization; attempted to call method 'refresh'

I am calling the refresh in a function that populates select lists with ajax content.

I've looked at using another event instead of pageshow but none seem appropriate.

Here are the relevant bits of code:

        //attach all listeners on dynamically loaded pages here
    $('[data-role=page]').live('pageshow', function(event, ui){ 
        //do stuff (get data, get select options, index of current selected
            $('select.myselect').fillSelect(itemsArray,indexofSelected);

    ...
    )}; //pageshow

This is the function I开发者_Python百科 sue to populate the select:

$.fn.fillSelect = function (items,index){
    //generically fills a select list - requires an array and target element optional index of selected element
    this.find('option').remove();
    var options = "";
    for (var i = 0; i < items.length; i++) {
            var selected = (index == i) ? 'selected="selected"' : "" ;
            options += '<option '+selected+'value="'+items[i]+'">'+items[i]+'</option>';
    } 
    //assembling html first cause appends are expensive
    this.append(options).selectmenu('refresh', true);

    return this;
}

Again this is specific to going directly to hash urls but works perfectly otherwise.


That's because you bind the pageshow event too late. It's already shown. To be sure it works put your bits of code in a file loaded before jquery mobile and make sure you don't wait for DOMready to call $('[data-role=page]').live('pageshow' ... live is the only thing that will work even if the selector gets you an empty result due to not loaded DOM.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜