2021-8-5 前端達人
在jQuery中可以使用2種方法來判斷一個元素是否包含一個確定的類(class)。兩種方法有著相同的功能。2種方法如下:(個人喜歡用hasClass())
1. hasClass(‘classname’)
2. is(‘.classname’)
以下是一個div元素是否包含一個redColor的例子:
$('div').is('.redColor')
$('div').hasClass('redColor')
以下是檢測一個元素是否含有一個redColor類的例子,含有時,則把其類變?yōu)閎lueColor。
<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的效果與初始效果相同。
文章來源:博客園
分享此文一切功德,皆悉回向給文章原作者及眾讀者.
免責聲明:藍藍設(shè)計尊重原作者,文章的版權(quán)歸原作者。如涉及版權(quán)問題,請及時與我們?nèi)〉寐?lián)系,我們立即更正或刪除。
藍藍設(shè)計( www.miumiuwan.com )是一家專注而深入的界面設(shè)計公司,為期望卓越的國內(nèi)外企業(yè)提供卓越的UI界面設(shè)計、BS界面設(shè)計 、 cs界面設(shè)計 、 ipad界面設(shè)計 、 包裝設(shè)計 、 圖標定制 、 用戶體驗 、交互設(shè)計、 網(wǎng)站建設(shè) 、平面設(shè)計服務
藍藍設(shè)計的小編 http://www.miumiuwan.com