JQuery .hasClass用于if语句中的多个值 [英] JQuery .hasClass for multiple values in an if statement

查看:272
本文介绍了JQuery .hasClass用于if语句中的多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的if语句:

I have a simple if statement as such:

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

// do stuff 

}

这可以按预期工作。但是,我想在 if语句中添加更多类,以检查< html> 标签。我需要它所以它不是全部而是只有至少一个类的存在但它可以更多。

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.

我的用例是我有课程(例如 m320 m768 )为各种视口宽度添加,所以我只想执行某个Jquery,如果它是一个特定的宽度(类)。

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

这是我到目前为止尝试过的:

Here is what i have tried so far:

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 .hasClass用于if语句中的多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆