JQuery中设置class相关的有如下三个方法:

$(selector).addClass();       // 向被选元素添加一个或多个类

$(selector).removeClass();    // 从被选元素删除一个或多个类

$(selector).toggleClass();    // 对被选元素进行添加/删除类的切换操作

下面实例演示一下以上三个方法的用法:

创建Html元素

点击不同按钮后,观察效果:

list-item-1list-item-2list-item-3list-item-4list-item-5

简单设置css样式

div.box{width:300px;height:300px;padding:10px 20px;border:4px dashed #ccc;}

div.box>span{color:#999;font-style:italic;}

div.content{width:250px;height:100px;margin:10px 0;padding:5px 20px;border:1px solid green;}

input{margin:10px;}

input[type='button']{width:200px;height:35px;margin:10px;border:2px solid #ebbcbe;}

.red{color:red;}

编写jquery代码

$(function(){

$("input:button.btn1").click(function() {

$(".content li:odd").addClass('red');

});

$("input:button.btn2").click(function() {

$(".content li").toggleClass('red');

});

$("input:button.btn3").click(function() {

$(".content li").removeClass('red');

});

})

观察显示效果

初始样式

点击第一个按钮,给偶数位置的列表项目添加red类

点击第二个按钮,有red类的元素去除red类,没有的就加上red类

点击第三个按钮,删除所有的red类

更多推荐

jq修改class_JQuery中怎么设置class