简体   繁体   English

jQuery更改类后继续选择元素

[英]jquery keeps on selecting element after changing the class

I have a button which must change what it does after meeting some condition. 我有一个按钮,必须满足某些条件后才能更改它的功能。

So I'm selecting the button by it's class and I want to remove that class upon meeting the condition and add a new class to the element and do something else with it. 因此,我要按按钮的类来选择按钮,并希望在满足条件时删除该类,并向该元素添加一个新类并对其进行其他操作。 but it's not working. 但它不起作用。

I just made up an example for my problem. 我只是为我的问题举了一个例子。

this is the code: 这是代码:

$('.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');
});

and it's Fiddle 这是小提琴

I expect this to toggle between increasing and decreasing the black box width, but it keeps on increasing. 我希望这会在增加和减少黑匣子宽度之间切换,但是会继续增加。

That's because the event is bound statically on the button, use event delegation like this: 这是因为事件是静态绑定在按钮上的,请使用如下的事件委托:

$(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');
});

DEMO DEMO

Offcourse you could do it like that...but isn't it easier to add an another variable that checks whether or not there has been a click? 当然,您可以这样做……但是添加另一个变量来检查是否有点击是否难吗? The code is much simpler and you can check later on whether or not the box has been enlarged. 该代码更加简单,您可以稍后检查该框是否已放大。

This method also seperates style from computing, which is generally regarded as a good idea. 这种方法也将样式与计算分开,这通常被认为是一个好主意。

var large = false;
$('body').on('click', '.button', function(){

if (large) {
    $('.box').addClass('clicked');
    large = false;
} else {
    $('.box').removeClass('clicked');
    large = true;
}

});

additionally, you need a css class like so: 另外,您需要像这样的css类:

.clicked {
    width: 110px; 
}

and I removed that button-1 and button-2 classes, gave the div the class 'button' instead 我删除了button-1和button-2类,给div分配了“ button”类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM