Use mouse 'on click' instead of 'mouse over' event, jquery

折月煮酒 提交于 2019-12-25 00:18:25

问题


I have this script here which works fine, but I need to make it work on mouse click instead of mouse hover.

I have tried, but failed. It looks simple, but I can't figure it out. Can anyone help?

code is:

$(".cat").hover(function(){
    $(this).parent().parent().find(".sub_menu").hide();
},
function() {
    $(this).parent().parent().find(".sub_menu").show();
});`

code below works in ie, not in firefox.

$(".cat").on('click', function(){
    $(this).parent().parent().find(".sub_menu").toggle();
});

回答1:


Try this

$(".cat").on('click', function(e){
    e.preventDefault();
    $(this).parent().parent().find(".sub_menu").toggle();
});

You can replace the .parent() by using .closest() if the HTML structure is known..

OR

$(".cat").on('click', function(e){
        e.preventDefault();
        $(this).closest('.menu').find(".sub_menu").toggle();
 });

WORKING DEMO




回答2:


$(".cat").on('click', function(){
    $(this).parent().parent().find(".sub_menu").toggle();
});


来源:https://stackoverflow.com/questions/13078782/use-mouse-on-click-instead-of-mouse-over-event-jquery

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