jQuery中addClass()方法用法实例


本文向大家介绍jQuery中addClass()方法用法实例,包括了jQuery中addClass()方法用法实例的使用技巧和注意事项,需要的朋友参考一下

本文实例讲述了jQuery中addClass()方法用法。分享给大家供大家参考。具体分析如下:

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

语法结构一:

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

$(selector).addClass(class)

参数列表:

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

实例代码:


<!DOCTYPE html>

<html>

<head>

<meta charset=" utf-8">

<meta name="author" content="https://www.yiidian.com/" />

<title>addClass函数-呐喊教程</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="https://www.yiidian.com/" />

<title>addClass()函数-呐喊教程</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>

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

希望本文所述对大家的jQuery程序设计有所帮助。