简体   繁体   English

jQuery-检测div是否有2个类

[英]jQuery - detect if div has 2 classes

I am using jQuery to detect a click like this.. 我正在使用jQuery来检测这样的点击。

$(".clickable_link").click(function() {
    console.log('Link Clicked');
}

<div class="clickable_link">
    Click Me
</div>

<div class="clickable_link special">
    Click Me
</div>

I am trying to determine if the div with 'special' has been clicked or if it just the div with 'clickable_link'. 我试图确定是否已单击具有“特殊”的div或仅仅是具有“ clickable_link”的div。

What is the best way to do this? 做这个的最好方式是什么? Should I use hasclass or is filter a better choice? 我应该使用hasclass还是filter是更好的选择?

Something like this: 像这样:

 $(".click").click(function(){ if ($(this).hasClass("special")) { alert("Its Special!"); } }); 
 .click { width:100px; height:50px; background-color:#333; float:left; margin:10px; color:#fff; text-align:center; padding-top:25px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="click">Not Special</div> <div class="click special">SPECIAL!</div> 

As an alternative to .hasClass , you can use .is , which allows for any selector, not just checking for a class. 作为一种替代.hasClass ,您可以使用.is ,它允许任何选择,不只是检查一类。

if($(this).is(".special")) { ...

 $(".clickable_link").click(function() { if ($(this).is(".special")) { alert("special clicked"); } else { alert("nope"); } }); 
 .special { color: red; } .clickable_link { cursor: pointer; margin-bottom: 0.5em; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="clickable_link"> Click Me </div> <div class="clickable_link special"> Click Me </div> 

 $('#id1').click(function() { var x = $('#id1').attr('class') //dont use classname to fetch the element x = x.split(' ') if (x.length > 2) alert('id1 has more than 2 classes'); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='id1' class='myclass mysubclass'>dfdfdfsdfds</div> 

You can bind different event handlers depending on whether the special class exists. 您可以根据special类是否存在来绑定不同的事件处理程序。

$(".clickable_link.special").click(function()
    console.log("Special link clicked");
})
$(".clickable_link:not(.special)").click(function() {
    console.log("Ordinary link clicked");
});

If there's common code for both types of links, you can put that in another function that gets called by each handler. 如果两种链接都有通用的代码,则可以将其放在每个处理程序调用的另一个函数中。

As example, use can can detect count of classes as like it: 例如,use可以像这样检测类的数量:

$(".clickable_link").click(function() {
    var classList = $(this).attr('class').split(/\s+/);
    console.log(`count ${classList.length}`);
}

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

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