简体   繁体   English

使用Jquery查找被单击项的类

[英]Find the class of the clicked item using Jquery

I have the following code: 我有以下代码:

    $(".perf-row").click(function(e) {
      if (e.target.tagName.toLowerCase() == "a") {
        pageTracker._trackPageview($(this).attr("rel"));
        return true; //link clicked
      } else {
        window.open($(this).attr("rel"));return false;
      }
    }); 

to the conditional statment of if (e.target.tagName.toLowerCase() == "a") i would like to also add "OR class is equal to price". if (e.target.tagName.toLowerCase() == "a")的条件语句中,我还要添加“ OR类等于价格”。

I'm not quite sure how to do that, i can't seem to find the class of the clicked element (which will be a td inside the table row). 我不太确定该怎么做,我似乎找不到被单击元素的类(在表行中是一个td)。

i've tried $(this).class , $(this.class) but neither work.... 我试过$(this).class$(this.class)但是都没有用....

Help would be greatly appreciated! 帮助将不胜感激!

若要查看元素是否具有.price类,请使用$.hasClass()方法。

$(this).hasClass("price");

You could combine both your tests into a single jQuery command: 您可以将两个测试合并为一个jQuery命令:

if( $(e.target).is('.price, a') ) { .... }

That tests if the target is either has the class price , or is an a tag, or is both. 一个测试,如果目标是既具有类price ,或者是a标签,或者兼而有之。 If you wanted to test that it was an a tag and had the price class, you would use this: 如果您想测试它是a标签并且具有price类别,则可以使用以下代码:

if( $(e.target).is('a.price') ) { .... }

Update: I may have misread your question. 更新:我可能误解了您的问题。 If you were going to add this second test to the same if test, then use my code. 如果要将第二个测试添加到相同的if测试中,请使用我的代码。 If you wanted to add a else if then use the .hasClass method as explained by the other answers. 如果要添加else if则使用.hasClass方法,如其他答案所述。

you can try: 你可以试试:

$(this).attr("class");

but this will return you names of all the classes applied to the element. 但这将返回您应用于该元素的所有类的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM