addClass()方法的定义和用法:
此方法向匹配元素添加一个或多个类。
此方法有多个语法形式。
语法结构一:
为匹配元素添加指定的类名。如果要一次性添加多个类名,它们之间要用空格分隔。
$(selector).addClass(class)
参数列表:
参数
描述
class
定义被添加类的名称
实例代码:
<!DOCTYPE html><html><head><metacharset="utf-8"><metaname="author"content="http://www.51texiao.cn/"/><title>蚂蚁部落</title><styletype="text/CSS">div{height:200px;width:200px;}.border{border:1px solid red;}.reset{font-size:20px;color:green;}</style><scripttype="text/javascript"src="mytest/jQuery/jquery-1.8.3.js"></script><scripttype="text/Javascript">$(document).ready(function(){
$("#btn").click(function(){
$("div").addClass("border reset");
})
})</script></head><body><div>蚂蚁部落欢迎您</div><buttonid="btn">点击查看效果</button></body></html>
以上代码可以为div添加两个类,能够设置div的边框和字体的样式。
语法结构二:
以函数的返回值作为要添加的类名。
$(selector).addClass(function(index,oldclass))
参数列表:
参数
描述
function(index,oldclass)
函数定义返回需要添加的一个或多个类名。
index - 可选,接受选择器的索引位置。
oldclass- 可选,接受选择器的当前的类名。
实例代码:
<!DOCTYPE html><html><head><metacharset="utf-8"><metaname="author"content="http://www.51texiao.cn/"/><title>蚂蚁部落</title><styletype="text/css">div{height:200px;width:200px;}.border{border:1px solid red;}.reset{font-size:20px;color:green;}</style><scripttype="text/javascript"src="mytest/jQuery/jquery-1.8.3.js"></script><scripttype="text/javascript">$(document).ready(function(){
$("#btn").click(function(){
$("div").addClass(function(){return"border reset";
})
})
})</script></head><body><div>蚂蚁部落欢迎您</div><buttonid="btn">点击查看效果</button></body></html>
上面代码和第一个实例的功能是一样的,只不过要添加的类是通过函数返回值得到的。
原文地址是:http://www.51texiao.cn/jqueryjiaocheng/2015/0613/4201.html
最为原始地址是:http://www.softwhy.com/forum.php?mod=viewthread&tid=5321