使用 jquery 检查元素上是否存在类“active”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6911594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a class `active` exist on element with jquery
提问by esafwan
Check if a class active
exist on an li
with a class menu
检查一个类是否active
存在于li
一个类上menu
For example
例如
<li class="menu active">something...</li>
回答by Richard Dalton
I think you want to use hasClass()
我想你想使用 hasClass()
$('li.menu').hasClass('active');
回答by Johan
You can retrieve all elements having the 'active' class using the following:
您可以使用以下方法检索所有具有 'active' 类的元素:
$('.active')
Checking wether or not there are any would, i belief, be with
检查是否有任何会,我相信,与
if($('.active').length > 0)
{
// code
}
回答by andyb
$('li.menu.active')
is the simplest way. This will return all elements with both classes.
是最简单的方法。这将返回具有两个类的所有元素。
Or an already answered jQuery hasClass() - check for more than one class
或者已经回答的jQuery hasClass() - 检查多个类
回答by a'r
You can use the hasClass
method, eg.
您可以使用该hasClass
方法,例如。
$('li.menu').hasClass('active') // true|false
Or if you want to select it in one go, you can use:
或者,如果您想一次性选择它,您可以使用:
$('li.menu.active')
回答by Simon Arnold
Pure Javascriptanswer:
纯 Javascript答案:
document.getElementsByClassName("menu").classList.contains("active");
Might help someone someday.
有一天可能会帮助某人。
回答by Nwachukwu A. Nnaemeka
if($('selector').hasClass('active')){ }
i think this will check if the selector hasClass active ...
我认为这将检查选择器 hasClass 是否处于活动状态...
回答by Scott
$(document).ready(function()
{
changeColor = $(.active).css("color","any color");
if($(".classname").hasClass('active')) {
$(this).eq(changeColor);
}
});
回答by sushil bharwani
use the hasClass jQuery method
使用 hasClass jQuery 方法
回答by Jay Patel
If Condition to check, currently class active or not
如果要检查条件,当前类是否处于活动状态
$('#next').click(function(){
if($('p:last').hasClass('active'){
$('.active').removeClass();
}else{
$('.active').addClass();
}
});
回答by Greg
i wrote a helper method to help me go through all my selected elements and remove the active class.
我编写了一个辅助方法来帮助我浏览所有选定的元素并删除活动类。
function removeClassFromElem(classSelect, classToRemove){
$(classSelect).each(function(){
var currElem=$(this);
if(currElem.hasClass(classToRemove)){
currElem.removeClass(classToRemove);
}
});
}
//usage
removeClassFromElem('.someclass', 'active');