如何用这个JS函数删除类
How to remove class with this JS function
设置此函数时,它只需在菜单选项集的类中找到-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');
});
相关文章:
- 使用删除函数.这不起作用
- Javascript minifier删除函数
- 无法访问要传递给删除函数的正确 Firebase 项键
- KNOCKOUTJS 映射插件从对象中删除函数
- 如何从匿名函数中删除函数的属性
- 如何在 PopConconfirm 中单击按钮 yes 时调用在 Angular 控制器中声明的删除函数
- 二叉搜索树 JavaScript 实现 - 删除函数
- JavaScript 删除函数无效
- jQuery:在特定窗口大小中添加或删除函数
- 如何从构造函数中删除函数
- Javascript - 从输入标签中删除函数
- 在更改状态 AngularJS 时删除函数
- 删除函数原型对象
- 可以't删除函数的映射部分
- 通过函数引用删除函数中的所有事件侦听器
- 删除函数内参数后面的对象
- 获取Closure / Plovr以从始终为false的if中删除函数
- 删除函数中的子DOM元素
- 改进JS重复数据删除函数的性能
- 如何从调用堆栈中删除函数并并行运行它