【发布时间】:2015-07-20 23:45:50
【问题描述】:
每当用户点击body 时,我想为某个元素添加一个类,只要该元素没有特定的类。问题是,我重用了这个元素,其中一些元素将具有我提到的特定类,而其他元素则没有。如果一个元素有这个类,用我当前的代码,没有元素会添加新的类。
Here is a fiddle showing the behaviour.
例子:
$('body').on('click', function(){
if ($('.box').hasClass('red') && !$('.box').hasClass('stay-red')) {
$('.box').addClass('blue');
}
});
html, body {
background: lightblue;
height: 100%;
}
.box {
height: 20px;
width: 20px;
margin-bottom: 10px;
}
.red {
background: red;
}
.blue {
background: blue;
}
<div class="box red stay-red"></div>
<div class="box red"></div>
【问题讨论】:
-
使用
.each方法作为$('.box')返回数组而不是单个元素 -
假设删除 .red 类 on.blue 是值得的)
-
但是如果你除了基于类的选择之外没有做太多的 DOM 操作,那么直接使用下面给出的 css 选择器/过滤器
标签: javascript jquery css dom-manipulation