码迷,mamicode.com
首页 > Web开发 > 详细

jQuery的addClass()方法

时间:2015-08-12 01:11:51      阅读:752      评论:0      收藏:0      [点我收藏+]

标签:

addClass()方法的定义和用法:

此方法向匹配元素添加一个或多个类。

此方法有多个语法形式。

语法结构一:

为匹配元素添加指定的类名。如果要一次性添加多个类名,它们之间要用空格分隔。

$(selector).addClass(class)

参数列表:

参数 描述
class 定义被添加类的名称

实例代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.51texiao.cn/" />
<title>蚂蚁部落</title>
<style type="text/css">
div{
  height:200px;
  width:200px;
}
.border{
  border:1px solid red;
}
.reset{
  font-size:20px;
  color:green;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("#btn").click(function(){
    $("div").addClass("border reset");
  })
})
</script>
</head>
<body>
<div>蚂蚁部落欢迎您</div>
<button id="btn">点击查看效果</button>
</body>
</html>

以上代码可以为div添加两个类,能够设置div的边框和字体的样式。

语法结构二:

以函数的返回值作为要添加的类名。

$(selector).addClass(function(index,oldclass))

参数列表:

 

参数 描述
function(index,oldclass) 函数定义返回需要添加的一个或多个类名。
index - 可选,接受选择器的索引位置。
oldclass- 可选,接受选择器的当前的类名。

实例代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.51texiao.cn/" />
<title>蚂蚁部落</title>
<style type="text/css">
div{
  height:200px;
  width:200px;
}
.border{
  border:1px solid red;
}
.reset{
  font-size:20px;
  color:green;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("#btn").click(function(){
    $("div").addClass(function(){
      return "border reset";
    })
  })
})
</script>
</head>
<body>
  <div>蚂蚁部落欢迎您</div>
  <button id="btn">点击查看效果</button>
</body>
</html>

上面代码和第一个实例的功能是一样的,只不过要添加的类是通过函数返回值得到的。

原文地址是:http://www.51texiao.cn/jqueryjiaocheng/2015/0613/4201.html

最为原始地址是:http://www.softwhy.com/forum.php?mod=viewthread&tid=5321

jQuery的addClass()方法

标签:

原文地址:http://www.cnblogs.com/softwhy/p/4722850.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!