Jquery click event not working on mobile device

允我心安 提交于 2021-01-28 00:58:43

问题


I am trying to make the below JSFiddle work for tablet/mobile devices (e.g. 'on touch' as well as 'click').

https://jsfiddle.net/lkw274/7zt1zL0g/87/


<div class="user-navigation">
        <a class="mobile-menu-new" href=""><span></span>Menu</a>
</div>

$(document).ready(function() {
$(".user-navigation a.mobile-menu-new").click(function (e) {
      e.preventDefault();
    $(".user-navigation a.mobile-menu-new").toggleClass("current");
    }); 
});

.current { background: #F00;}

Expected behaviour: On clicking 'Menu', either by touch or with clicked with mouse, the background is highlighted red until it is clicked again when the class should be removed, removing the red background and returning it to its original state.

Current behaviour: On clicking 'Menu', by touch on mobile/tablet device, the background is highlighted red however the class is not removed when 'menu' is clicked for the second time.

Could anyone help to understand how this code needs to be modified for tablet/mobile devices?

I have tried the solution in the below StackOverflow link however this did not function on click once implemented.

document-click-function-for-touch-device

Thanks in advance.


回答1:


Looks like event delegation is the way to do this since, when you modify the target element, bind seems to fail.

Try the following (works on my iPhone/Chrome).

$(document).ready(function() {
    $(".user-navigation").delegate("a.mobile-menu-new", "click", function (e) {
        e.preventDefault();
        $(this).toggleClass("current");
    });
});

Please note I have used .delegate since you seem to be using jQuery 1.6 (as per your fiddle) as otherwise, with jQuery 1.7+, you could use .on like below.

$(document).ready(function() {
    $(".user-navigation").on("click", "a.mobile-menu-new", function (e) {
        e.preventDefault();
        $(this).toggleClass("current");
    });
});



回答2:


add the cursor:pointer to the property of your class and it should work find in mobile

.user-navigation{ cursor:pointer }




回答3:


$(selector).bind("click touchstart", function(){
       .......
});


来源:https://stackoverflow.com/questions/30057551/jquery-click-event-not-working-on-mobile-device

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