我有一个按钮,它必须在满足某些条件后改变它的行为。
所以我通过它的类选择按钮,我想在满足条件时删除那个类,并为元素添加一个新类,并对它做其他事情。但这行不通。
我只是为我的问题编了一个例子。
这是代码:
$('.button-1').click(function(){
$('.box').width(function(){
return $(this).width() + 10;
});
$(this).removeClass('button-1').addClass('button-2');
});
$('.button-2').click(function(){
$('.box').width(function(){
return $(this).width() - 10;
});
$(this).removeClass('button-2').addClass('button-1');
});
是Fiddle
我希望它在增加和减少黑框宽度之间切换,但它一直在增加
这是因为事件是静态绑定在按钮上的,所以像这样使用事件委托:
$(document).on('click','.button-1', function(){
$('.box').width(function(){
return $(this).width() + 10;
});
$(this).removeClass('button-1').addClass('button-2');
});
$(document).on('click','.button-2', function(){
$('.box').width(function(){
return $(this).width() - 10;
});
$(this).removeClass('button-2').addClass('button-1');
});
当然你可以这样做…但是,添加另一个变量来检查是否发生了点击不是更容易吗?代码要简单得多,您可以稍后检查框是否被放大。
该方法还将样式从计算中分离出来,这通常被认为是一个好主意。
var large = false;
$('body').on('click', '.button', function(){
if (large) {
$('.box').addClass('clicked');
large = false;
} else {
$('.box').removeClass('clicked');
large = true;
}
});
另外,你需要一个CSS类,像这样:
.clicked {
width: 110px;
}
,我删除了button-1和button-2类,给div命名为button