怎麼使用jquery判斷一個元素是否含有一個指定的類(class)

來源:互聯網
上載者:User

標籤:img   判斷   this   包含   ack   方法   rip   query   低版本   

在jQuery中可以使用2種方法來判斷一個元素是否包含一個確定的類(class)。兩種方法有著相同的功能。2種方法如下:(個人喜歡用hasClass())

1.           hasClass(‘classname’)

2.           is(‘.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的效果與初始效果相同。

怎麼使用jquery判斷一個元素是否含有一個指定的類(class)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.