Click event doesnt work in safari mobile for some HTML content

别来无恙 提交于 2019-12-19 10:04:20

问题


In my web app, there is a separate navbar for mobile devices. I want this navbar to collapse when the menu button is clicked or anywhere else in the site is clicked. It already works in any mobile browser but not it safari mobile (In safari also, for home page it works but not in other pages). In other pages, there are some html generated dynamically. It seems that the click event doesn't work for those content. I'd really appreciate a solution for this problem. the code is as follows. I've tried 'body', $(document), window instead of $('html'). It doesn't for them also.

$('html').click(function(event) {
            var clickover = $(event.target);
var $navbar = $(".navbar-collapse");               
var _opened = $navbar.hasClass("in");
if (_opened === true && !clickover.hasClass("navbar-toggle")) {      
    $navbar.collapse('hide');
}
        });

I've also tried what is mentioned in Fixing jQuery Click Events for the iPad. But the code mentioned in there doesn't trigger at all. The code I've tried for this as belows.

var ua = navigator.userAgent,
event = (ua.match(/iPad/i)) ? "touchstart" : "click";

$('body').bind(event, function(e) {
            var clickover = $(event.target);
var $navbar = $(".navbar-collapse");               
var _opened = $navbar.hasClass("in");
if (_opened === true && !clickover.hasClass("navbar-toggle")) {      
    $navbar.collapse('hide');
}

}

I'd really appreciate an answer for my question (I was working on this for more than a day but didn't find a solution).


回答1:


Anyway I finally found a solution. The reason was, iPhone Safari doesnt support event delegation. What my initial requirement was to trigger the click event when the body of the HTML is clicked. Anyway the issue was only occurring on Safari mobile and the reason I found was, Safari doesn't support event delegation for the click event. I solved it by adding below code in the body CSS.

cursor: pointer;

Thre resources I got the answer were, Click event delegation on the iPhone

and

jQuery click events not working in iOS : Answer

And Dohab, Thank you for your answer too.




回答2:


You can create a div container for the entire page, and bind it to a click event.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#container").click(function(){
        $(this).hide();
    });
});
</script>
</head>
<body>
    <div id="container">
        <p>If you click anywhere. I will hide</p>
        ...
        ...

    </div>
</body>
</html>


来源:https://stackoverflow.com/questions/39243513/click-event-doesnt-work-in-safari-mobile-for-some-html-content

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