jQuery中addClass()方法用法執行個體,jqueryaddclass

來源:互聯網
上載者:User

jQuery中addClass()方法用法執行個體,jqueryaddclass

本文執行個體講述了jQuery中addClass()方法用法。分享給大家供大家參考。具體分析如下:

此方法向匹配元素添加一個或多個類。
此方法有多個文法形式。

文法結構一:

為匹配元素添加指定的類名。如果要一次性添加多個類名,它們之間要用空格分隔。
複製代碼 代碼如下:$(selector).addClass(class)

參數列表:

參數 描述
class 定義被添加類的名稱

執行個體代碼:

複製代碼 代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.bkjia.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="http://www.bkjia.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程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.