Javascript 用于 if 语句中多个值的 JQuery .hasClass
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10559153/
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
JQuery .hasClass for multiple values in an if statement
提问by Danny Englander
I have a simple if statement as such:
我有一个简单的 if 语句:
if ($('html').hasClass('m320')) {
// do stuff
}
This works as expected. However, I want to add more classes to the if statement
to check if any of the classes are present in the <html>
tag. I need it so it's not all of them but just the presence of at least one class but it can be more.
这按预期工作。但是,我想向 中添加更多类以if statement
检查<html>
标记中是否存在任何类。我需要它,所以它不是全部,而只是至少存在一个类,但它可以更多。
My use case is that I have classes (e.g. m320
, m768
) added for various viewport widths so I only want to execute certain Jquery if it's a specific width (class).
我的用例是我为各种视口宽度添加了类(例如m320
,m768
),所以我只想执行特定的 Jquery,如果它是特定的宽度(类)。
Here is what i have tried so far:
这是我迄今为止尝试过的:
1.
1.
if ($('html').hasClass('m320', 'm768')) {
// do stuff
}
2.
2.
if ($('html').hasClass('m320')) || ($('html').hasClass('m768')) {
// do stuff
}
3.
3.
if ($('html').hasClass(['m320', 'm768'])) {
// do stuff
}
None of these seem to work though. Not sure what I am doing wrong but most likely my syntax or structure.
不过,这些似乎都不起作用。不确定我做错了什么,但很可能是我的语法或结构。
采纳答案by James Montagne
You just had some messed up parentheses in your 2nd attempt.
在第二次尝试中,您只是将括号弄乱了。
var $html = $("html");
if ($html.hasClass('m320') || $html.hasClass('m768')) {
// do stuff
}
回答by elclanrs
You could use is()
instead of hasClass()
:
您可以使用is()
代替hasClass()
:
if ($('html').is('.m320, .m768')) { ... }
回答by jfriend00
For fun, I wrote a little jQuery add-on method that will check for any one of multiple class names:
为了好玩,我写了一个小的 jQuery 附加方法来检查多个类名中的任何一个:
$.fn.hasAnyClass = function() {
for (var i = 0; i < arguments.length; i++) {
if (this.hasClass(arguments[i])) {
return true;
}
}
return false;
}
Then, in your example, you could use this:
然后,在你的例子中,你可以使用这个:
if ($('html').hasAnyClass('m320', 'm768')) {
// do stuff
}
You can pass as many class names as you want.
您可以根据需要传递任意数量的类名。
Here's an enhanced version that also lets you pass multiple class names separated by a space:
这是一个增强版本,它还允许您传递由空格分隔的多个类名:
$.fn.hasAnyClass = function() {
for (var i = 0; i < arguments.length; i++) {
var classes = arguments[i].split(" ");
for (var j = 0; j < classes.length; j++) {
if (this.hasClass(classes[j])) {
return true;
}
}
}
return false;
}
if ($('html').hasAnyClass('m320 m768')) {
// do stuff
}
Working demo: http://jsfiddle.net/jfriend00/uvtSA/
回答by Kolja
This may be another solution:
这可能是另一种解决方案:
if ($('html').attr('class').match(/m320|m768/)) {
// do stuff
}
according to jsperf.comit's quite fast, too.
根据jsperf.com,它也非常快。
回答by Ryan Steffer
For anyone wondering about some of the different performance aspects with all of these different options, I've created a jsperf case here: jsperf
对于任何想知道所有这些不同选项的不同性能方面的人,我在这里创建了一个 jsperf 案例:jsperf
In short, using element.hasClass('class')
is the fastest.
总之,使用element.hasClass('class')
是最快的。
Next best bet is using elem.hasClass('classA') || elem.hasClass('classB')
. A note on this one: order matters! If the class 'classA' is more likely to be found, list it first! OR condition statements return as soon as one of them is met.
下一个最好的选择是使用elem.hasClass('classA') || elem.hasClass('classB')
. 关于这一点的说明:订单很重要!如果更有可能找到“classA”类,请先列出它!OR 条件语句只要满足其中之一就返回。
The worst performance by far was using element.is('.class')
.
迄今为止最糟糕的性能是使用element.is('.class')
.
Also listed in the jsperf is CyberMonk's function, and Kolja's solution.
jsperf 中还列出了CyberMonk 的功能和Kolja 的解决方案。
回答by CyberMonk
Here is a slight variation on answer offered by jfriend00:
以下是 jfriend00 提供的答案的细微变化:
$.fn.hasAnyClass = function() {
var classes = arguments[0].split(" ");
for (var i = 0; i < classes.length; i++) {
if (this.hasClass(classes[i])) {
return true;
}
}
return false;
}
Allows use of same syntax as .addClass() and .removeClass(). e.g., .hasAnyClass('m320 m768')
Needs bulletproofing, of course, as it assumes at least one argument.
允许使用与 .addClass() 和 .removeClass() 相同的语法。例如,.hasAnyClass('m320 m768')
当然需要防弹,因为它假设至少有一个论点。
回答by Robert ?oziński
Try this:
尝试这个:
if ($('html').hasClass('class1 class2')) {
// do stuff
}
回答by qwerty_igor
I've tested multiple classes in a parameter of hasClass method and it works as expected.
我已经在 hasClass 方法的参数中测试了多个类,它按预期工作。
$('el').hasClass('first-class second-class');
This is in case you need both classes present. For either or logic just use ||
这是在您需要两个类都存在的情况下。对于或逻辑只使用 ||
$('el').hasClass('first-class') || $('el').hasClass('second-class')
Feel free to optimize as needed
根据需要随意优化
回答by Ron Sims II
The hasClass method will accept an array of class names as an argument, you can do something like this:
hasClass 方法将接受一个类名数组作为参数,您可以执行以下操作:
$(document).ready(function() {
function filterFilesList() {
var rows = $('.file-row');
var checked = $("#filterControls :checkbox:checked");
if (checked.length) {
var criteriaCollection = [];
checked.each(function() {
criteriaCollection.push($(this).val());
});
rows.each(function() {
var row = $(this);
var rowMatch = row.hasClass(criteriaCollection);
if (rowMatch) {
row.show();
} else {
row.hide(200);
}
});
} else {
rows.each(function() {
$(this).show();
});
}
}
$("#filterControls :checkbox").click(filterFilesList);
filterFilesList();
});
回答by adeneo
var classes = $('html')[0].className;
if (classes.indexOf('m320') != -1 || classes.indexOf('m768') != -1) {
//do something
}