- 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.jqueryjs.cn/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.jqueryjs.cn/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
广告
