简体   繁体   English

如果有X类,请不要添加新的Y类

[英]If there is a X class don't add a new Y class

I am a little confused with my JS (I am very new working with JS). 我对我的JS有点困惑(我是JS的新手)。

I already have 我已经有了

$('#left-nav-menu').hover(function () {
  $(this).toggleClass('menu-desktop_open_hover')
});

I would like to achieve if there already is this class "menu-desktop_open_hover" and you click on the DIV with this class "menu-desktop_open_hover" DO NOT add a new class called "menu-desktop_open" 我想实现是否已存在此类“ menu-desktop_open_hover”,并且单击具有此类“ menu-desktop_open_hover”的DIV不要添加新的名为“ menu-desktop_open”的类

By default when you click the DIV with the class "menu-desktop_open_hover" it is adding a new class called "menu-desktop_open" (we need to keep this class for another things but not when the div is mouse-over/mouse-out) 默认情况下,当您单击类别为“ menu-desktop_open_hover”的DIV时,它会添加一个名为“ menu-desktop_open”的新类别(我们需要保留该类别用于其他用途,但是当div鼠标悬停/鼠标移出时则不需要)

Do anyone know how could I achieve it? 有人知道我怎么能做到吗?

Thanks 谢谢

You can use jQuery hasClass() 您可以使用jQuery hasClass()

$('div').on('click', function() {
  if ( $(this).hasClass("menu-desktop_open_hover") ) {
     //Do something if it's true the class is applied...
  }
});

Thank you @ProEvilz 谢谢@ProEvilz

Below my final code and it is working! 在我的最终代码下面,它正在工作!

 $('#left-nav-menu').hover( function() { $(this).toggleClass('menu-desktop_open_hover') } ); $('#left-nav-menu').on('click', function() { if ($(this).hasClass("menu-desktop_open_hover")) { $("#left-nav-menu").removeClass("menu-desktop_open"); } }); 

You can use toggle like this: 您可以像这样使用切换:

$('div').on('click', function() {
  if ( $(this).hasClass("menu-desktop_open_hover") ) {
     $(this).toggleClass("menu-desktop_open");  // toggleClass() will help you.
  }
});

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

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