62

我有一个点击事件,我想分配给更多的班级。这样做的原因是我在我的应用程序的不同位置使用此事件,并且您单击的按钮在不同位置具有不同的样式。

我想要的是 $('.tag' '.tag2') 之类的东西,这当然行不通。

    $('.tag').click(function (){
        if ($(this).hasClass('clickedTag')){
            // code here
        }

        else {
             // and here
        }
    });
4

6 回答 6

118

方法#1

function doSomething(){
    if ($(this).hasClass('clickedTag')){
        // code here
    }
    else {
         // and here
    }
}

$('.tag1').click(doSomething);
$('.tag2').click(doSomething);

// or, simplifying further
$(".tag1, .tag2").click(doSomething);

方法#2

这也将起作用:

​$(".tag1, .tag2").click(function(){
   alert("clicked");    
});​

小提琴

如果有可能重用逻辑,我更喜欢单独的函数(方法#1)。

另请参阅如何选择具有多个类的元素?用于处理同一项目的多个类。

于 2012-05-09T07:49:35.000 回答
11

您可以使用 jQuery 一次选择多个类,如下所示:

$('.tag, .tag2').click(function() {
    var $this = $(this);
    if ($this.hasClass('tag')) {
        // do stuff
    } else {
        // do other stuff
    }
});

为 $()​​ 函数提供第二个参数,将选择器的范围限定为在具有 class 的元素中$('.tag', '.tag2')查找。tagtag2

于 2012-05-09T07:52:00.100 回答
7
    $('.tag1, .tag2').on('click', function() {

      if ($(this).hasClass('clickedTag')){
         // code here
      } else {
         // and here
      }

   });

或者

function dothing() {
   if ($(this).hasClass('clickedTag')){
        // code here
    } else {
        // and here
   }
}

$('.tag1, .tag2').on('click', dothing);

或者

 $('[class^=tag]').on('click', dothing);
于 2012-05-09T07:55:59.140 回答
5

就像这样:

$('.tag.clickedTag').click(function (){ 
 // this will catch with two classes
}

$('.tag.clickedTag.otherclass').click(function (){ 
 // this will catch with three classes
}

$('.tag:not(.clickedTag)').click(function (){ 
 // this will catch tag without clickedTag
}
于 2012-05-09T07:50:34.967 回答
1

你有没有试过这个:

 function doSomething() {
     if ($(this).hasClass('clickedTag')){
         // code here
     } else {
         // and here
     }
 }

 $('.tag1, .tag2').click(doSomething);
于 2012-05-09T07:52:08.373 回答
1
    $('[class*="tag"]').live('click', function() {
      if ($(this).hasClass('clickedTag')){
         // code here
      } else {
         // and here
      }
   });
于 2012-05-09T07:59:52.023 回答