简体   繁体   English

jQuery父母都有这两个类

[英]jQuery parents has both classes

I'm trying to create an if statement for <a> tags that have two classes. 我正在尝试为具有两个类的<a>标签创建if语句。 I've successfully implemented the following to check for one class: 我已经成功实现了以下内容来检查一个类:

if ($("a").parents().hasClass("class1")) {
                // do something...
            }

But how do you look for an element that has two classes, for example an element that had class1 and class2? 但是,如何查找具有两个类的元素,例如具有class1 class2?的元素class2? I know in CSS it would be .class1.class2{} , but not sure how in JavaScript? 我知道在CSS中它将是.class1.class2{} ,但不确定在JavaScript中如何?

Here you are: 这个给你:

 alert($('#b2').hasClass('c1 c2 c3')); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="b2" type="text" placeholder="Enter Name." name="name" maxlength="300" class="c1 c2 c3" /> 

Hope this helps. 希望这可以帮助。

Try the .is() method. 尝试.is()方法。

// or any selector you want to check against.
if ($("a").parents().is(".class1.class2")) { 
  // do something
}

If you want to use the same methods, another way to do this would be with a double ampersand "&&": 如果要使用相同的方法,则另一种方法是使用双“&”符号:

if (($("a").parents().hasClass("class1")) && ($("a").parents().hasClass("class2"))) {
            // do something...
        }

It's a bit more code than previous examples, but it should be a good fail-safe! 它比以前的示例多了一些代码,但它应该是一个很好的故障保护方法!

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

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