【问题标题】:Use mouse 'on click' instead of 'mouse over' event, jquery使用鼠标“点击”而不是“鼠标悬停”事件,jquery
【发布时间】:2012-10-16 05:43:16
【问题描述】:

我有这个脚本 here 可以正常工作,但我需要让它在鼠标单击而不是鼠标悬停时工作。

我尝试过,但失败了。它看起来很简单,但我无法弄清楚。有人可以帮忙吗?

代码是:

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

下面的代码在 ie 中工作,而不是在 firefox 中。

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

【问题讨论】:

  • 能否请您将不起作用的代码添加到问题中? (点击标签下方的“编辑”按钮。)这意味着该问题将来仍然有用。

标签: jquery mousehover onmouseclick


【解决方案1】:

试试这个

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

如果 HTML 结构已知,您可以使用 .closest() 替换 .parent()..

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

WORKING DEMO

【讨论】:

  • Adeneo 的解决方案在 firefox 中不起作用(在 ie 中起作用),所以我将使用 Sushanth 的 .closest()。谢谢!
【解决方案2】:
$(".cat").on('click', function(){
    $(this).parent().parent().find(".sub_menu").toggle();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多