JQuery Mobile 1.3.1 “$.mobile.loading” not working

假如想象 提交于 2019-12-03 10:41:18
Gajotres

What jQuery Mobile documentation is lacking information regarding successful execution of:

$.mobile.loading('show');

and

$.mobile.loading('hide');

They will show ONLY during the pageshow event. In any other case you need to wrap them into the setinterval, like this:

In case you don't know anything about pageshow and rest of jQuery Mobile page events take a look at this ARTICLE, it is my personal blog. Or find it HERE.

First, you will not be able to show/hide AJAX loader without set interval. There's is only one situation where this is possible without and that is during the pageshow event. In any other case setinterval is needed to kick start the loader.

Here's a working example: http://jsfiddle.net/Gajotres/Zr7Gf/

    var interval = setInterval(function(){
        $.mobile.loading('show');
        clearInterval(interval);
    },1);    

    var interval = setInterval(function(){
        $.mobile.loading('hide');
        clearInterval(interval);
    },1);      

Wrapping it in setTimeout works. I just have a simple function to do it:

function loading(showOrHide) {
    setTimeout(function(){
        $.mobile.loading(showOrHide);
    }, 1); 
}

Then just call it when you want to show or hide the spinner:

loading('show');

or

loading('hide');

Here's a silly jsfiddle: http://jsfiddle.net/7UpW5/

Inside AJAX call? (but will work anywhere)

$.ajax({ url: ..., 
    type:'post', dataType:'json',
    data:{ d: ... }, 
    beforeSend: function() { fSpinner('show'); },
    complete: function(){ fSpinner('hide'); },
    success: function( res ){...},
    error: function(e){ alert('Error: ' + e.responseText) }
});

And the function itself:

function fSpinner( strShowOrHide ) {
    setTimeout( function(){
        $.mobile.loading( strShowOrHide );
    }, 1); 
}

the code for the other answers did not work for me and is not complete (e.g. if you like to pass parameters eventually or just use boolean true/false for toggling. The following provides a nice way to do this:

/** workaround: $.mobile.loading not working correctly: http://stackoverflow.com/a/17725350 */
function showLoading( on, params ) {  // on: true|false
    setTimeout( function() {
      if ( on )
        $.mobile.loading( "show", params );
      else {
        //$.mobile.loading( "hide" );  // does not seem to work (e.g. using with GWT and jQM 1.4.3)
        $('.ui-loader').remove();  // removes the loader div from the body
      }       
    }, 1);
}

use it like this:

showLoading( true );  // show loader
showLoading( false );  // hide loader
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!