jQuery mobile (click event)

2019-02-18 07:24发布

问题:

I'm developing smartphone hybrid applications.

I'm trying to hide/show a <div> with slideDown/slideUp.

When I click on the button, the menu <div> is supposed to hide/show depend of the context. Everything is working well on my computer but it just doesn't work at all on my mobile, nothing happens.

Here is my HTML code

<a class="btnMenuDyn" data-role="button">Masquer le menu</a>

and here my jQuery mobile code:

$(document).bind('pageinit', function(e){


// définition des variables
var btnMenuDyn = $('a.btnMenuDyn'),
    menuDyn = $('div.menuDyn');

$(btnMenuDyn).bind('click', function(){


    // condition pour afficher ou non le menu
    if ($(menuDyn).hasClass("menuDynHide"))
    {
        $(menuDyn).slideDown().removeClass("menuDynHide");
    }
    else{
        $(menuDyn).slideUp().addClass("menuDynHide");
    }

});
});

回答1:

this problem is mobiles do not support click they use touchstart and touchend so can track movement if you still want to test on computers you can do this

$(btnMenuDyn).bind('touchstart mousedown', function(event){
    event.preventDefault();
    if ($(menuDyn).hasClass("menuDynHide"))
    {
        $(menuDyn).slideDown().removeClass("menuDynHide");
    }
    else{
        $(menuDyn).slideUp().addClass("menuDynHide");
    }

});

another question with same answer jquery touchstart in browser

more infomation can be found at http://backtothecode.blogspot.com/2009/10/javascript-touch-and-gesture-events.html



回答2:

I would suggest using on() instead of bind()

And since youre doing this:

var btnMenuDyn = $('a.btnMenuDyn')

btnMenuDyn is a jquery dom element, so change this:

if ($(menuDyn).hasClass("menuDynHide"))

to this

if (menuDyn.hasClass("menuDynHide"))

And preferably declare jquery dom elements like this:

var $btnMenuDyn = $('a.btnMenuDyn')