由于您可能有许多 class 实例example
,因此仅使用单个变量来维护状态是不可行的,您可以做的是维护example
自身内部每个实例的状态:
定义两个css类
.example { background:blue }
.example.red { background:red }
然后你的点击方法:
$('.example').click(function(){
$(this).toggleClass('red');
});
如果您不想定义新的 css 类,您可以使用data()
, 来确保每个中的状态是独占的.example
,如果您有很多实例,这很有用.example
$('.example').click(function() {
var color = $(this).data('color');
if(color != 'blue') {
$(this).css('color', 'blue');
$(this).data('color', 'blue');
} else {
$(this).css('color', 'red');
$(this).data('color', 'red');
}
});
http://api.jquery.com/data/