返回值:jQueryaddClass(className)

Adds the specified class(es) to each of the set of matched elements.

It's important to note that this method does not replace a class. It simply adds the class, appending it to any which may already be assigned to the elements.

More than one class may be added at a time, separated by a space, to the set of matched elements, like so:

$('p').addClass('myClass yourClass');

This method is often used with .removeClass() to switch elements' classes from one to another, like so:

$('p').removeClass('myClass noClass').addClass('yourClass');

Here, the myClass and noClass classes are removed from all paragraphs, while yourClass is added.

As of jQuery 1.4, the .addClass() method allows us to set the class name by passing in a function.

$('ul li:last').addClass(function() {
  return 'item-' + $(this).index();
});

Given an unordered list with five <li> elements, this example adds the class "item-4" to the last <li>.

示例:

Adds the class 'selected' to the matched elements.

<!DOCTYPE html>
<html>
<head>
<style>

  p { margin: 8px; font-size:16px; }
  .selected { color:blue; }
  .highlight { background:yellow; }
  </style>
<script src="jquery.min.js"></script>
</head>
<body>

<p>Hello</p>
  <p>and</p>
  <p>Goodbye</p>

<script>

$("p:last").addClass("selected");

</script>
</body>
</html>
演示:

示例:

Adds the classes 'selected' and 'highlight' to the matched elements.

<!DOCTYPE html>
<html>
<head>
<style>

  p { margin: 8px; font-size:16px; }
  .selected { color:red; }
  .highlight { background:yellow; }
  </style>
<script src="jquery.min.js"></script>
</head>
<body>

<p>Hello</p>
  <p>and</p>
  <p>Goodbye</p>

<script>

$("p:last").addClass("selected highlight");

</script>
</body>
</html>
演示: