jquery单击添加和删除类

时间:2014-05-30 02:41:00

标签: jquery

我有一个列表项,当我点击Li元素时,添加类“active”,其他人删除class

这是小提琴[http://fiddle.jshell.net/9yNtq/] 和代码

<div class="boxList">
                <table>
                <tr>
                    <td>
                        <a href="#" data-ajax="false"><span>list1</span></a>
                    </td>
                    <td>
                        <a href="#" data-ajax="false"><span>list2</span></a>
                    </td>
                    <td>
                        <a href="#" data-ajax="false"><span>list3</span></a>
                    </td> 
                </tr>  
                </table>
            </div>


.boxList { margin:5px 0 0 0;   }
.boxList table { table-layout:fixed; width:100%;   }
.boxList td { width:33.3%; padding:0; margin:0; text-align:center;  }

.boxList a {   width:100%; font-size:1.07em; font-weight:bold;  height:62px; color:#000; line-height:1.3;  }
.boxList a span {   padding:0; margin:0;  width:100%; height:62px;  }
.boxList a.active { background:blue }


$('.boxList a').click(function(){ 
                $('.boxList a').removeClass("active"); 
                $(this).addClass("active"); 
            });

我的问题是...... 如何在再次单击相同元素时删除“活动”类?

2 个答案:

答案 0 :(得分:4)

您可以使用toggleClass('classname')。您还需要使用.not()

从选择器中删除当前单击的元素
 $(this).toggleClass("active"); 

完整代码:

$('.boxList a').click(function(){ 
            $('.boxList a').not(this).removeClass("active"); 
            $(this).toggleClass("active"); 
});

<强> Working Demo

答案 1 :(得分:2)

你可能正在寻找这个......

$('.boxList a').click(function(){ 

 if($(this).hasClass('active')){       
    $('.boxList a').removeClass("active"); 
 }
 else{

    $('.boxList a').removeClass("active");         
    $(this).addClass("active"); 
 }
});

Here is Example

相关问题