怎么使⽤jquery判断⼀个元素是否含有⼀个指定的类(class)在中可以使⽤2种⽅法来判断⼀个元素是否包含⼀个确定的类(class)。两种⽅法有着相同的功能。2种⽅法如下:(个⼈喜欢⽤hasClass())
1. hasClass(‘classname’)
2. is(‘.classname’)
以下是⼀个div元素是否包含⼀个redColor的例⼦:
1. 使⽤is(‘.classname’)的⽅法
$('div').is('.redColor')
jquery ajax例子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 () {
});
</script>
</body>
</html>
初始效果:
点击is('.redColor')后的效果:
点击hasClass('redColor')的效果与点击is('.redColor')后的效果相同,点击reset的效果与初始效果相同。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论