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

原创 jQuery.removeClass() 函数详解

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

内容目录

removeClass()函数用于移除当前jQuery对象所匹配的每一个元素上指定的css类名

该函数属于jQuery对象(实例)。如果你需要为元素添加css类名,你可以使用addClass()函数。

语法

jQueryObject.removeClass( classNames )

注意removeClass()会移除当前jQuery对象所匹配的每一个元素上指定的css类名。

参数

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

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

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

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

返回值

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

如果需要移除的css类名并不存在,removeClass()函数就忽略掉该css类名。

示例&说明

以下面这段HTML代码为例:

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

我们编写如下jQuery代码:

var $n2 = $("#n2");
// 移除n2上的一个css类名
$n2.removeClass("demo");
document.writeln( $n2.attr("class") ); // test item-1

var $n3 = $("#n3");
// 移除n3上的3个css类名(类名"test"不存在,忽略该类名)
$n3.removeClass("foo bar test");
document.writeln( $n3.attr("class") ); // news item-2

// 按顺序移除所有p元素上的css类名"item-N",这里的N表示当前元素在所有匹配元素中的序号(1、2、3……)
$("p").removeClass( function(index, classNames){
	// 函数内的this表示当前DOM元素
	return "item-" + (index + 1);
} );

document.writeln( $("#n2").attr("class") ); // test
document.writeln( $("#n3").attr("class") ); // news

运行代码

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

0 条评论

撰写评论

打开导航菜单