我有一个简单的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.

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).

以下是我迄今为止try 过的:

1.

if ($('html').hasClass('m320', 'm768')) {

// do stuff 

}

2.

if ($('html').hasClass('m320')) || ($('html').hasClass('m768')) {

 // do stuff 

}

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.

推荐答案

You just had some messed up parentheses in your 2nd attempt.

var $html = $("html");

if ($html.hasClass('m320') || $html.hasClass('m768')) {

  // do stuff 

}

Jquery相关问答推荐

无法通过单击从元素获取数据

如何在Jquery和Laravel中使用请求传递两个参数给Datatable

如何限制select2中的字符?

第一次单击后,Ajax addEventListener 停止工作

在函数 jQuery 中更改语言

bootstrap 模式中的自动完成问题

$(document).ready(function() VS $(function(){

使用 jQuery 更改 CSS 类属性

如何知道所有ajax调用何时完成

如何从 jQuery 中的父级中 Select 所有子级(任何级别)?

使用跨域帖子发送凭据?

使html文本输入字段随着我输入而增长?

使用带有 HTML 表格的 jQuery UI 可排序

DataTables:无法读取未定义的属性长度

如何让 JavaScript/jQuery Intellisense 在 Visual Studio 2008 中工作?

!!~(不是波浪号/bang bang 波浪号)如何改变包含/包含数组方法调用的结果?

如何使用 JQuery $.scrollTo() 函数滚动窗口

你能在不影响历史的情况下使用哈希导航吗?

javascript,是否有像 isArray 这样的 isObject 函数?

jQuery 使用 AND 和 OR 运算符按属性 Select