简体   繁体   中英

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. Here is the example of all possible div's:

<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,

$('.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. Is there any ways to make proper check of this using 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 || :

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!")
         }
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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