jQuery移动错误“无法在初始化之前调用listview上的方法”

时间:2012-04-29 16:03:31

标签: listview jquery-mobile

我正在动态填充<ul data-role="listview">,然后调用列表所在的location.href="#Results",最后listview('refresh')

所有这些都是在同一页面的Ajax请求成功回调中完成的。它或多或少有效,但我收到以下错误:

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

我猜jQuery mobile还没有构建listview。我该怎么办?

7 个答案:

答案 0 :(得分:36)

首先不使用任何参数调用listview方法:

$('#myListview').listview().listview('refresh');

取自http://www.gajotres.net/uncaught-error-cannot-call-methods-on-prior-to-initialization-attempted-to-call-method-refresh/

的解决方案

答案 1 :(得分:28)

你应该检查它是否已经初始化,刷新列表以防它被初始化,否则触发按以下方式创建:

if ( $('#myListview').hasClass('ui-listview')) {
    $('#myListview').listview('refresh');
     } 
else {
    $('#myListview').trigger('create');
     }

答案 2 :(得分:14)

我有同样的错误。我通过在查询中添加“:visible”来解决它,因此只有在列表可见时才会运行。

所以你的代码看起来像这样:

$('#myListview:visible').listview('refresh');

对我来说很好!

答案 3 :(得分:10)

http://jquerymobile.com/demos/1.1.0/docs/api/events.html 你必须挂钩pageinit事件。在此之前,您无法调用任何JQM方法。 即:

$('#Results').bind('pageinit', function() {
  $('#myListview').listview('refresh');
});

答案 4 :(得分:2)

使用$.mobile.changePage("#Results");代替location.href
实际上location.href重新加载页面,以便列表视图被破坏

然后listview.refresh

答案 5 :(得分:0)

简单地添加listview.refresh对我来说很好,我也使用ajax将内容加载到div中。

document.getElementById("myListview").innerHTML = xmlhttp.responseText;
//works fine on my work
$('#myListview').listview('refresh');

这里是我的帖子。

jquery mobile ajax load content into a div element will lose it's css style

我花了将近3个小时来解决我的帖子问题。最后在这里找到答案。谢谢。

答案 6 :(得分:0)

这对我有用:

   $(document).delegate('#Results', 'pageshow', function (){
   $('#mylistview').listview('refresh').trigger('create'); 
   });