62

I have an click event that I want to assign to more than class. The reason for this is that I'm using this event on different places in my application, and the buttons you click have different styling in the different places.

What I want is something like $('.tag' '.tag2'), which of course don't work.

    $('.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
    }
});

$()関数に2番目のパラメーターを指定すると、セレクターのスコープが設定され、クラスを持つ要素内を$('.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 に答える