jQuery属性-addClass()方法

1.普通定义和用法

语法

$(selector).addClass(class)
参数 描述
class 必需。规定一个或多个 class 名称。

 

 

 

2.函数添加类:使用函数向被选元素添加类。

语法

$(selector).addClass(function(index,oldclass)
参数 描述
function(index,oldclass) 必需。规定返回一个或多个待添加类名的函数。
  •     index - 可选。选择器的 index 位置。
  •     class - 可选。选择器的旧的类名。

 

 

 

 

普通定义用法

 

<html>
<head>
  <script src="js/jquery.min.js"></script>
  <script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("p:first").addClass("example");
  });
});
</script>
  <style type="text/css">
    .example {
      color: red;
    }
  </style>
</head>
<body>
  <h1>Hello kayze-refresh</h1>
  <p>Hello kayze-refresh</p>
  <p>Hello kayze-refresh</p> <button>向第一个 p 元素添加一个类</button> </body> </html>

 

 

函数添加类用法

1、function(index)

index - 可选。选择器的 index 位置。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>learning notes</title>
    <script src="js/jquery.min.js"></script>
</head>
<style>
    body{
        color: #FFF;
    }
    .selected0{
        background: #008744;
    }
    .selected1{
        background: #0057e7;
    }
    .selected2{
        background: #d62d20;
    }
</style>
<body>
    <ul class="addClass">
        <li>Hello kayze-refresh</li>
        <li>Hello kayze-refresh</li>
        <li>Hello kayze-refresh</li>
    </ul>
<script> 
    $(function(){ 
    $('.addClass li').addClass(function(n){
        return 'selected' + n;
        });
    });
</script>
</body>
</html>

 

2、function(index,oldclass)

index - 可选。选择器的 index 位置。
class - 可选。选择器的旧的类名。

当需要添加类时的目标元素含有该类时,才会对包含该类的元素

使用该方法时,当目标元素含有 oldClass 类名时,才会添加类名的函数。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>learning notes</title>
    <script src="js/jquery.min.js"></script>
</head>
<style>
    body{
        color: #FFF;
    }
    .selected0{
        background: #008744;
    }
    .selected1{
        background: #0057e7;
    }
    .selected2{
        background: #d62d20;
    }
</style>
<body>
    <ul class="addClass">
        <li class="old">Hello kayze-refresh</li>
        <li>Hello kayze-refresh</li>
        <li>Hello kayze-refresh</li>
    </ul>
<script> 
    $(function(){ 
    $('.addClass li').addClass(function(n,old){
        return 'selected' + n;
        });
    });
</script>
</body>
</html>

 

我是菜鸟,有什么其他的看法请留言跟我说下,我会学习修改。

未完待续!

posted @ 2016-09-20 23:38  弓长沐戒  阅读(4258)  评论(0编辑  收藏  举报