为一个事件分配多个类

hol*_*ard 49 jquery events class

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

我想要的是像$('.tag''.tag2'),这当然不起作用.

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

        else {
             // and here
        }
    });
Run Code Online (Sandbox Code Playgroud)

Tim*_*ora 93

方法#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);
Run Code Online (Sandbox Code Playgroud)

方法#2

这也有效:

?$(".tag1, .tag2").click(function(){
   alert("clicked");    
});?
Run Code Online (Sandbox Code Playgroud)

小提琴

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

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


Jam*_*imm 8

您可以使用jQuery一次选择多个类:

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

给$()函数提供第二个参数,范围选择器以便在具有类的元素中$('.tag', '.tag2')查找.tagtag2


fms*_*msf 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
}
Run Code Online (Sandbox Code Playgroud)


the*_*dox 5

    $('.tag1, .tag2').on('click', function() {

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

   });
Run Code Online (Sandbox Code Playgroud)

要么

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

$('.tag1, .tag2').on('click', dothing);
Run Code Online (Sandbox Code Playgroud)

要么

 $('[class^=tag]').on('click', dothing);
Run Code Online (Sandbox Code Playgroud)