jQuery Mobile-直接转到哈希URL会导致动态元素失败 [英] jQuery Mobile - Going directly to hash URL causes dynamic elements to fail
问题描述
我遇到了一个问题,页面上的动态元素在"pageshow"上进行了更新.如果用户直接转到该URL或从站点中的其他地方导航到该URL,则此方法非常有用.问题是,如果我直接转到该页面或刷新它(例如:mydomain.com/#somepage.html),它将失败并且出现错误:
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:
未捕获的无法在初始化之前调用selectmenu上的方法;尝试调用方法刷新"
Uncaught cannot call methods on selectmenu prior to initialization; attempted to call method 'refresh'
我正在使用刷新功能调用刷新,该功能使用ajax内容填充选择列表.
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.
以下是相关的代码位:
//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 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.
推荐答案
这是因为您绑定pageshow事件太晚了.已经显示了.
为确保其正常工作,请将您的代码片段放入jquery mobile之前加载的文件中,并确保您不要等待DOMready调用$('[data-role=page]').live('pageshow' ...
即使选择器由于未加载DOM而使您得到空结果,live仍然是唯一有效的方法.
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.
这篇关于jQuery Mobile-直接转到哈希URL会导致动态元素失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!