如何用这个JS函数删除类

How to remove class with this JS function

本文关键字:删除 函数 JS 何用这      更新时间:2024-02-17

设置此函数时,它只需在菜单选项集的类中找到-a,然后单击即可添加"选定"类,并从该列表中的所有其他类中删除"选定"的类。

我想做的就是简单地拥有它,这样如果你点击已经有"selected"类的项目,它就会删除"selected"类。我知道它不应该是"return false";我只是把它作为占位符,因为我无法找到正确的编码。

谢谢大家!:)

var $optionSets = $('.menu-option-set'),
    $optionLinks = $optionSets.find('a');
$optionLinks.click(function() {
    var $this = $(this);
    // Remove Class if already selected --> this is the part that I need help with
    if ($this.hasClass('selected')) {
        return false;
    }
    var $optionSet = $this.parents('.menu-option-set');
    $optionSet.find('.selected').removeClass('selected');
    $this.addClass('selected');
});​
$('.menu-option-set a').click(function()
{
    // if clicked item is selected then deselect it
    if ($(this).hasClass('selected'))
    {
        $(this).removeClass('selected');
    }
    // otherwise deselect all and select just this one
    else
    {
        $('.menu-option-set a').removeClass('selected');
        $(this).addClass('selected');
    }
});

您应该只能使用$().removeClass('selected'),即

  if ( $this.hasClass('selected') ) {
      $this.removeClass('selected');
  }

但是,您稍后也将再次添加该类,因此这应该不是真正必要的。

您可以通过选择所有.selected元素、删除this和删除类来内联它。

$this
  .parents('.menu-option-set')
  .find('.selected')
  .not(this)
  .removeClass('selected');
$(this).addClass('selected');

或者,使用toggleClass()方法,如下所示:

var $optionSets = $('.menu-option-set'),
    $optionLinks = $optionSets.find('a');
$optionLinks.click(function() {
    var $this = $(this);
    var $optionSet = $this.parents('.menu-option-set');
    $optionSet.find('.selected').not(this).removeClass('selected');
    $this.toggleClass('selected');
});​

编辑:添加了.not(this),以排除单击的<li>在应该删除类之前将其删除。

如果你想简明扼要:

$('.menu-option-set a').click(function() {
    $(this).toggleClass('selected').siblings().removeClass('selected')​​;
});