简体   繁体   English

Javascript div类检查onclick

[英]Javascript div class check onclick

I am trying to check onclick if div have one of two different classes added to main div class and if there is no such - give back alert. 我正在尝试检查onclick是否div将两个不同的类之一添加到主div类中,如果没有,请返回警报。 Here is the example of all possible div's: 这是所有可能的div的示例:

<div class="mainclass class1"></div>
<div class="mainclass class2"></div>
<div class="mainclass"></div>

If I am trying to check for class existence using JS something like, 如果我尝试使用JS这样的类来检查类是否存在,

$('.mainclass').click(function () {
    var check1 = $(this).hasClass('class1');
    var check2 = $(this).hasClass('class2');
    if(check1 == false || check2 == false)
                { 
                    alert("Hey, you are clicking empty field!")
                }
});

System will always give back alert even if I will click on first two div's. 即使我单击前两个div,系统也会始终返回警报。 Is there any ways to make proper check of this using JS? 有什么方法可以使用JS进行适当的检查吗?

It's easier to apply these restrictions when selecting the object to be tracked: 在选择要跟踪的对象时,更容易应用以下限制:

$('.mainclass').not('.class1, .class2').click(function () {
  alert("Hey, you are clicking empty field!")
});

If these classes are indeed added/removed dynamically, again, state your intent directly: 如果确实确实动态添加/删除了这些类,请再次直接声明您的意图:

$('.mainclass').click(function() {
    if ( $(this).is(':not(.class1, .class2)') ) { 
        alert("Hey, you are clicking empty field!");
    }
});

Change the operator to && not || 将运算符更改为&&而不是|| :

$('.mainclass').click(function () {
var check1 = $(this).hasClass('class1');
var check2 = $(this).hasClass('class2');
if(check1 == false && check2 == false)
            { 
                alert("Hey, you are clicking empty field!")
            }
});

Working Demo 工作演示

You need AND && operator here instead of OR || 您在这里需要AND &&运算符,而不是OR || :

if(check1 == false && check2 == false)

Fiddle Demo 小提琴演示

Just check like this 像这样检查

$('.mainclass').click(function () {
    var check1 = $(this).hasClass('class1');
    var check2 = $(this).hasClass('class2');
    if(!check1 && !check2 )
                { 
                    alert("Hey, you are clicking empty field!")
                }
});

another Way 其他方式

$('.mainclass').click(function () {

    if(!$(this).hasClass('class1') && !$(this).hasClass('class2'))
         { 
            alert("Hey, you are clicking empty field!")
         }
 });

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

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