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>

 

我是菜鳥,有什么其他的看法請留言跟我說下,我會學習修改。

未完待續!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM