您的浏览器过于古老 & 陈旧。为了更好的访问体验, 请 升级你的浏览器
Ready 发布于2014年08月23日 05:59

原创 jQuery.addClass() 函数详解

4973 次浏览 读完需要≈ 6 分钟

内容目录

addClass()函数用于为当前jQuery对象所匹配的每一个元素添加指定的css类名

该函数属于jQuery对象(实例)。如果你需要删除元素上的css类名,你可以使用removeClass()函数。

语法

jQueryObject.addClass( classNames )

注意addClass()会为当前jQuery对象所匹配的每一个元素添加指定的css类名。

参数

参数 描述
classNames String/Function类型指定的css类名,字符串可以通过空格分隔的方式来添加多个css类名。或者为返回css类名的函数

jQuery 1.4 新增支持:参数classNames可以为函数。addClass()将根据匹配的所有元素遍历执行该函数,函数中的this将指向对应的DOM元素。

addClass()还会为函数传入两个参数:第一个参数就是该元素在匹配元素中的索引,第二个参数就是该元素节点当前的class属性值。

函数的返回值就是为该元素添加的css类名(也可以通过空格分隔表示多个css类名)。如果返回值为空白字符串或者undefinedaddClass()将不会为当前元素添加任何css类名。

返回值

addClass()函数的返回值是jQuery类型,返回当前jQuery对象本身。

addClass()函数只是在原有css类名的基础上,添加新的css类名,并不会覆盖掉之前已存在的css类名。如果待添加的css类名已经存在,addClass()并不会重复添加。

示例&说明

以下面这段HTML代码为例:

<div id="n1">
   	<p id="n2" class="demo test">CodePlayer</p>
   	<p id="n3" class="foo">专注于编程开发技术分享</p>
</div>

我们编写如下jQuery代码:

var $n2 = $("#n2");
// 为n2添加一个css类名
$n2.addClass("newOne");
document.writeln( $n2.attr("class") ); // demo test newOne

var $n3 = $("#n3");
// 为n3添加3个css类名
$n3.addClass("test class1 class2");
document.writeln( $n3.attr("class") ); // foo test class1 class2

// 为所有p标签添加css类名"item-index",这里的index表示当前元素在所有匹配元素中的索引
$("p").addClass( function(index, classNames){
	// 函数内的this表示当前DOM元素
	return "item-" + index;
} );

document.writeln( $("#n2").attr("class") ); // demo test newOne item-0
document.writeln( $("#n3").attr("class") ); // foo test class1 class2 item-1

运行代码

  • CodePlayer技术交流群1
  • CodePlayer技术交流群2

0 条评论

撰写评论

打开导航菜单