在添加类之前,使用jQuery从元素中删除类

在添加类之前,使用jQuery从元素中删除类,jquery,addclass,Jquery,Addclass,因此,我有一个网页,您可以在其中选择文本框,然后通过再次单击背景或框来关闭它们: 因此,我有一些代码可以根据单击的内容添加或删除类: $('li').click(function(){ _this = $(this) if (_this.hasClass('active')) { //Close it if you clicked on that's already open _this.removeClass('active') } e

因此,我有一个网页,您可以在其中选择文本框,然后通过再次单击背景或框来关闭它们:

因此,我有一些代码可以根据单击的内容添加或删除类:

$('li').click(function(){
    _this = $(this)
    if (_this.hasClass('active')) {
        //Close it if you clicked on that's already open
        _this.removeClass('active')
    } else if ($('li.active').length !== 0) {
        //close one and open another one you clicked
        _this.siblings().removeClass('active')
        _this.siblings().bind('webkitTransitionEnd oTransitionEnd transitionend',function(){
            _this.addClass('active');
        });
    } else {
        //open the first one
        _this.addClass('active');
    }

});

//Close when clicking the background
$('#close').click(function(){
    $('.active').removeClass('active')
});
问题:当您打开一个框并再次单击它时,它应该会自动关闭,就像第一条if语句所说的那样。但是,如果在文本框之间切换3次(利用seconds if语句),并尝试关闭第三个文本框,它就会一次又一次地重新打开自己。关于它为什么会这样做有什么线索吗

谢谢

弄明白了

即使处于不同的if语句中,转换事件处理程序也不会解除绑定。进行了一些阅读,按照jQuery的创建者的建议,将.bind()和.unbind()移动到.on()和.off(),并将off语句添加到on语句函数的末尾

代码如下:

$('li').click(function(){
    _this = $(this)
    if (_this.hasClass('active')) {
        //Close it if you clicked on that's already open
        _this.removeClass('active')
    } else if ($('li.active').length !== 0) {
        //close one and open another one you clicked
        _this.siblings().removeClass('active')
        _this.siblings().on('webkitTransitionEnd oTransitionEnd transitionend',function(){
            _this.addClass('active');
            _this.siblings().off('webkitTransitionEnd oTransitionEnd transitionend');
        });
    } else {
        //open the first one
        _this.addClass('active');
    }

});

//Close when clicking the background
$('#close').click(function(){
    $('.active').removeClass('active')
});

您的url似乎工作正常,您的代码是否与您提供的url不一样?您是否连续在三个文本框之间切换?之后,问题就出现了。代码是相同的+注释。我认为你应该做
.length!=0
而不是
.length!==0
Yupp,这是一个不完整的设计。但感谢你的“建设性批评”。我的上述评论是对一条现已删除的评论的回应,该评论抱怨未完成页面背景的颜色。