javascript - 检查jquery中哪个类被点击

标签 javascript jquery

假设我有一个 anchor 标记,每个标记中有两个不同的类

<a class="class1 class2">Click me</a>
<a class="class1 class3">Click me</a>

我想知道如果我点击class1 anchor ,它是否有class2class3

我尝试了这个,但它没有执行

$(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/

相关文章:

javascript - Drupal 页面上的 jQuery 代码无法在 IE 中运行?

javascript - HTML表格,单独编辑记录

javascript - typescript 错误#70006,类型引用任何

javascript - 如何使用 jQuery Mobile 动态创建单选按钮?

javascript - 将字符串拆分为 n 个单词的数组

jquery - 如何通过 jQuery 中的另一个附加元素访问附加元素

javascript - 当用户在搜索栏上键入内容时,如何显示/隐藏文本区域值?

javascript - 动态动画的问题

php - 根据用户的时间设置问候语(早上好,下午好……)

javascript - Jquery "THIS".myFuntionName 在 ajax 中不可用 成功?但之前还好