假设我有一个 anchor 标记,每个标记中有两个不同的类
<a class="class1 class2">Click me</a>
<a class="class1 class3">Click me</a>
我想知道如果我点击class1
anchor ,它是否有class2
或class3
我尝试了这个,但它没有执行
$(document).ready(function()
{
$('.class1').click(function()
{
if($(this).has('class2'))
{
alert("class2 tag");
}
else
{
alert("class3 tag");
}
});
});
最佳答案
您应该使用 jquery 的 hasClass
方法,而不是 has
:
$(document).ready(function() {
$('.class1').click(function() {
if ($(this).hasClass('class2')) {
alert("class2 tag");
} else {
alert("class3 tag");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="class1 class2">Click me</a>
<a class="class1 class3">Click me</a>
因为您只搜索类名,所以 hasClass
就足够了。
这里可能应该避免 has
的原因是 has
旨在减少一组匹配的元素。以下是 jquery 文档中的方法描述:
.has()
Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.
关于javascript - 检查jquery中哪个类被点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41724509/