zoukankan      html  css  js  c++  java
  • 怎么使用jquery判断一个元素是否含有一个指定的类(class)

    jQuery中可以使用2种方法来判断一个元素是否包含一个确定的类(class)。两种方法有着相同的功能。2种方法如下:

    1.           is(‘.classname’)

    2.           hasClass(‘classname’)

    以下是一个div元素是否包含一个redColor的例子:

    1. 使用is(‘.classname’)的方法

    $('div').is('.redColor')

    2. 使用hasClass(‘classname’)的方法(注意jquery的低版本可能是hasClass(‘.classname’))

    $('div').hasClass('redColor')

    以下是检测一个元素是否含有一个redColor类的例子,含有时,则把其类变为blueColor

    <html>
    <head>
    <styletype="text/css">
      .redColor { 
            background:red;
      }
      .blueColor { 
            background:blue;
      }
    </style>
    <scripttype="text/javascript"src="jquery-1.3.2.min.js"></script>
    </head>
    <body>
      <h1>jQuery check if an element has a certain class</h1>
     
      <divclass="redColor">This is a div tag with class name of "redColor"</div>
     
      <p>
      <buttonid="isTest">is('.redColor')</button>
      <buttonid="hasClassTest">hasClass('.redColor')</button>
      <buttonid="reset">reset</button>
      </p>
    <scripttype="text/javascript">
     
        $("#isTest").click(function () {
     
              if($('div').is('.redColor')){
                    $('div').addClass('blueColor');
              }
     
        });
     
        $("#hasClassTest").click(function () {
     
              if($('div').hasClass('redColor')){
                    $('div').addClass('blueColor');
              }
     
        });
     
            $("#reset").click(function () {
              location.reload();
        });
     
     
    </script>
    </body>
    </html>

     初始效果:


    点击is('.redColor')后的效果:


    点击hasClass('redColor')的效果与点击is('.redColor')后的效果相同,点击reset的效果与初始效果相同。

  • 相关阅读:
    [ solr入门 ] 在schema.xml中加入自己的分词工具
    SQLServer2005获取大数据集时内存不足的解决办法[转]
    java位操作基本教程[转]
    log4j的最佳实践(转)
    [ lucene扩展 ] "Did you mean" feature with Apache Lucene SpellChecker
    java image filters[02]过滤器初探
    PHP serialize 和 JSON 解析与区别
    js 实现 静态缓存页面中访问动态IP下载地址
    smarty section foreach遍历多维数组
    【转】window.open 参数
  • 原文地址:https://www.cnblogs.com/zknublx/p/7010620.html
Copyright © 2011-2022 走看看