为一个事件分配多个类 [英] Assigning more than one class for one event

查看:123
本文介绍了为一个事件分配多个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个点击事件,我想分配给超过类。原因是我在我的应用程序的不同地方使用此事件,并且您点击的按钮在不同的地方有不同的样式。

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.

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

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
        }
    });


推荐答案

方法#1



Approach #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



工作:

Approach #2

This will also work:

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

小提示

我喜欢一个单独的函数(方法#1),如果有机会逻辑将

I prefer a separate function (approach #1) if there is a chance that logic will be reused.

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

See also How can I select an element with multiple classes? for handling multiple classes on the same item.

这篇关于为一个事件分配多个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆