DIV CSS 佈局教程網

用 jQuery 為多個不同元素同時加上 class
編輯:JQuery特效代碼     

本文示範如何利用 jQuery 的 addClass() 方法,一次為多個不同的 HTML 元素同時加上相同的 class。

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("h1,h2,p").addClass("blue");
    $("div").addClass("important");
  });
});
</script>
<style type="text/css">
.important { font-weight:bold; font-size:xx-large; }
.blue { color:blue; }
</style>
</head>
<body>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<p>This is a paragraph.</p>
<div>This is some important text!</div>
<br>
<button>Add classes to elements</button>
</body>
</html>

由於 jQuery 選擇器可一次選到多個元素(如 $("h1,h2,p")),對這群元素呼叫 addClass() 就能批次套用樣式,省去逐一設定的麻煩。希望本文對大家的 jQuery 開發有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved