最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery on click not working FireFox - possibly event.preventdefault - Stack Overflow

programmeradmin4浏览0评论

I have the following which is working on every browser other than Firefox. This appears to be a problem the prevent default action, how can I fix this?

$(".subcontent .sidebar .mobileopen").on("click", function () {
    event.preventDefault();
    $('.subcontent .sidebar .mobileopen').toggleClass('removeborder');
    $('.subcontent .sidebar nav.mobile').slideToggle();
    $('.subcontent .sidebar nav.mobile ul li.menu-item-has-children > a').on("click", function () {
        event.preventDefault();
        $(this).nextAll('ul').eq(0).slideToggle('slow');
        $(this).parent().toggleClass("open");
    });
});

I have the following which is working on every browser other than Firefox. This appears to be a problem the prevent default action, how can I fix this?

$(".subcontent .sidebar .mobileopen").on("click", function () {
    event.preventDefault();
    $('.subcontent .sidebar .mobileopen').toggleClass('removeborder');
    $('.subcontent .sidebar nav.mobile').slideToggle();
    $('.subcontent .sidebar nav.mobile ul li.menu-item-has-children > a').on("click", function () {
        event.preventDefault();
        $(this).nextAll('ul').eq(0).slideToggle('slow');
        $(this).parent().toggleClass("open");
    });
});
Share Improve this question edited Sep 15, 2019 at 18:34 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Oct 19, 2015 at 14:59 bigdaveygeorgebigdaveygeorge 1,0092 gold badges15 silver badges35 bronze badges 3
  • 2 $( ".subcontent .sidebar .mobileopen" ).on( "click", function(event) { dont know if this helps. But you need to apply the event on the function – Tommy Commented Oct 19, 2015 at 15:00
  • event should be a parameter to the handler function, is what @Tommy correctly suggests :) – Pointy Commented Oct 19, 2015 at 15:00
  • Take a look here: stackoverflow./questions/4585970/… – Dalibor Commented Oct 19, 2015 at 15:03
Add a ment  | 

2 Answers 2

Reset to default 5

You haven't passed the event parameter to the event handler

$(".subcontent .sidebar .mobileopen").on("click", function (event) {
                                                            ^^^^^
    event.preventDefault();

Mozilla Firefox don't have global event. Check https://stackoverflow./a/33167145/2025923.

You can also use return false; at the end of the event handler to prevent default action of the element from happening. This will also stop event bubbling.

This one worked for me

$("body").on("click", ".subcontent .sidebar .mobileopen" function (event) {
    event.preventDefault();

});
发布评论

评论列表(0)

  1. 暂无评论