jQuery添加class、删除class


关键词

jQuery 添加class 删除class 判断class

摘要

本文介绍在jQuery中如何判断一个对象是否有某个class,以及如何添加class,删除class。

下面是源代码,运行时,点击段落文字,系统会判断如果当前包含了red这个class,则将其删除,如果没有包含red,则添加一个red的class。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="gb2312" />
<title>hello world</title>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js "></script>
<script type="text/javascript">
$(document).ready(function(){

    $("#p1").on('click',function(){
        if($("#p1").hasClass('red')){
            $('#p1').removeClass('red');
        }else{
            $('#p1').addClass('red');
        }
    });

});
</script>
<style>
.red{ color:red; }
</style>
</head>

<body>
<div id="p1" class="blue red">点击这一段内容试试</div>
</body>
</html>

 

要饭二维码

洪哥写文章很苦逼,如果本文对您略有帮助,可以扫描下方二维码支持洪哥!金额随意,先行谢过!大家的支持是我前进的动力!

文章的版权

本文属于“洪哥笔记”原创文章,转载请注明来源地址:jQuery添加class、删除class:http://www.splaybow.com/post/jquery-class-add-remove-hasclass.html

如果您在服务器运维、网络管理、网站或系统开发过程有需要提供收费服务,请加QQ:8771947!十年运维经验,帮您省钱、让您放心!
亲,如果有需要,先存起来,方便以后再看啊!加入收藏夹的话,按Ctrl+D

« jQuery绑定元素的事情 jQuery二级分类联动 »