- jQuery 教程
- jQuery - 首頁
- jQuery - 路線圖
- jQuery - 概述
- jQuery - 基礎
- jQuery - 語法
- jQuery - 選擇器
- jQuery - 事件
- jQuery - 屬性
- jQuery - AJAX
- jQuery DOM 操作
- jQuery - DOM
- jQuery - 新增元素
- jQuery - 刪除元素
- jQuery - 替換元素
- jQuery CSS 操作
- jQuery - CSS 類
- jQuery - 尺寸
- jQuery - CSS 屬性
- jQuery 效果
- jQuery - 效果
- jQuery - 動畫
- jQuery - 鏈式操作
- jQuery - 回撥函式
- jQuery 遍歷
- jQuery - 遍歷
- jQuery - 遍歷祖先節點
- jQuery - 遍歷子孫節點
- jQuery UI
- jQuery - 互動
- jQuery - 小部件
- jQuery - 主題
- jQuery 參考
- jQuery - 選擇器
- jQuery - 事件
- jQuery - 效果
- jQuery - HTML/CSS
- jQuery - 遍歷
- jQuery - 其他
- jQuery - 屬性
- jQuery - 工具函式
- jQuery 外掛
- jQuery - 外掛
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
- jQuery 有用資源
- jQuery - 問答
- jQuery - 快速指南
- jQuery - 有用資源
- jQuery - 討論
jQuery hasClass() 方法
jQuery 中的 hasClass() 方法用於檢查任何選定的元素是否具有指定的類名。它檢查 jQuery 物件中的任何元素是否具有指定的類名。
語法
以下是 jQuery 中 hasClass() 方法的語法:
$(selector).hasClass(classname)
引數
此方法接受以下引數:
- classname: 表示要檢查的類名的字串。
返回值
如果任何選定的元素具有指定的類名,則該方法返回 true;否則,返回 false。
示例 1
在下面的示例中,我們使用 hasClass() 方法來檢查任何 <div> 元素是否具有名為“highlight”的類:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
if ($('div').hasClass('highlight')) {
alert("A div with the class 'highlight' exist.");
} else {
alert("A div with the class 'highlight' does not exist.");
}
})
});
</script>
</head>
<body>
<div class="highlight">Div element with class "highlight".</div>
<div class="one">Div element with class "one".</div>
<div class="two">Div element with class "two".</div>
<button>Click to check</button>
</body>
</html>
當我們單擊按鈕時,它會返回一個警報,指出存在一個名為“highlight”的類的 <div> 元素。
示例 2
在這裡,我們檢查任何 <p> 元素是否具有名為“highlight”的類:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$('p').each(function(){
if ($(this).hasClass('highlight')) {
$(this).css("background-color", "yellow");
}
});
});
});
</script>
</head>
<body>
<p class="highlight">Paragraph element with class "highlight".</p>
<p class="one">Paragraph element with class "one".</p>
<p class="two">Paragraph element with class "two".</p>
<button>Click to check</button>
</body>
</html>
單擊按鈕後,它會將具有名為“highlight”的類的 <p> 元素突出顯示為黃色背景。
jquery_ref_html.htm
廣告
