0

设置此功能,因此它只需在 menu-option-set 类中找到 -a's-,并说,单击时,添加“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');
});​
4

4 回答 4

1

你应该可以使用$().removeClass('selected')ie

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

但是,您稍后还会再次添加该类,因此这实际上不是必需的。

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

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

$(this).addClass('selected');
于 2012-07-24T07:43:53.707 回答
1
$('.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');
    }
});
于 2012-07-24T07:47:05.380 回答
0

或者,使用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>的类在它应该被删除之前。

于 2012-07-24T07:45:08.947 回答
0

如果你想简洁:

$('.menu-option-set a').click(function() {
    $(this).toggleClass('selected').siblings().removeClass('selected')​​;
});
于 2012-07-24T08:11:10.263 回答