简体   繁体   English

为什么这段jQuery代码不起作用?

[英]Why doesn't this piece of jQuery code work?

Just the first function works. 只是第一个功能起作用。 When I click again on the button nothing happens. 当我再次单击该按钮时,没有任何反应。 The console always prints 1. 控制台始终打印1。

$('#mobile-menu:not(.active)').click(
  function (e) {
    $('#wrapper').addClass('show-menu');
    $(this).addClass('active');
    $('#sidebar').show();
    e.preventDefault();
    console.log(1);
  }
);
$('#mobile-menu.active').click(
  function (e) {
    $('#wrapper').removeClass('show-menu');
    $(this).removeClass('active');
    $('#sidebar').hide();
    e.preventDefault();
    console.log(2);
  }
);

Because you're binding directly to nothing. 因为您直接绑定到任何东西。 Adding active does not switch the event. 添加活动不会切换事件。 Here's what you want: 这就是您想要的:

$('#mobile-menu').click(
    function (e) {
        var notActive = ! $(this).hasClass('active');
        $('#wrapper').toggleClass('show-menu', notActive);
        $(this).toggleClass('active', notActive);
        // This is what I had originally
        //$('#sidebar')[notActive ? 'show' : 'hide']();
        $('#sidebar').toggle(notActive); // per @ᾠῗᵲᄐᶌ
        e.preventDefault();
        console.log(notActive ? 1 : 2);
    }
);

Use delegation 使用委托

$('body').on('click', '#mobile-menu:not(.active)',function(){

});

$('body').on('click', '#mobile-menu.active',function(){

});

Or you can bind to the element using the ID and check if it has the class 或者,您可以使用ID绑定到元素,并检查它是否具有类

$('#mobile-menu').click(function(){
    if($(this).hasClass('active')){

    }else{

    }    
});

When you assign the click handlers your selector only selects those elements that are .active and assigns a click handler to them. 分配单击处理程序时,选择器只会选择.active元素,并为其分配一个单击处理程序。 the other click handler finds no elements, and so is not assigned. 其他点击处理程序未找到任何元素,因此未分配。 You need one handler that performs both functions: 您需要一个执行两种功能的处理程序:

$('#mobile-menu').click(
  function (e) {
    e.preventDefault();
    if (!$(this).hasClass("active")) {
      $('#wrapper').addClass('show-menu');
      $(this).addClass('active');
      $('#sidebar').show();
      console.log(1);
    } else {
      $('#wrapper').removeClass('show-menu');
      $(this).removeClass('active');
      $('#sidebar').hide();
      console.log(2);
    }
  }
);

Your selector $('#mobile-menu.active') is referring to something that doesn't exist yet, so your second function actually doesn't do anything. 您的选择器$('#mobile-menu.active')指的是尚不存在的东西,因此您的第二个功能实际上什么也没做。

You can achieve what you want like this: 您可以这样实现您想要的:

$('#mobile-menu').click(function(){
  if($(this).hasClass('active')) {
    // Do stuff
  } else {
    // Do other stuff
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM