How to write a switch statement in jQuery/Javascri

2019-03-25 14:00发布

问题:

This is the structure of the if-else statement I am using:

$('.myclass a').click(function() {
   if ($(this).hasClass('class1')) {
        //do something
   } else if ($(this).hasClass('class2')) {
        //do something
   } else if ($(this).hasClass('class3')) {
        //do something
   } else if ($(this).hasClass('class4')) {
        //do something
   } else {
        //do something
   }
});

There are quite a number of cases already and I thought using a switch statement would be neater. How do I do it in jQuery/javascript?

回答1:

The problem is that an user could have more than one class. Otherwise you could do:

$('.myclass a').click(function() {
   var className = $(this).attr('class');
   switch(className){
      case 'class1':
     //put your cases here
   }
});


回答2:

Try this. Not much cleaner, but still a switch statement.

$('.myclass a').click(function() {
    switch (true) {
      case $(this).hasClass('class1'):
        // do stuff
        break;
      case $(this).hasClass('class2'):
        // do stuff
        break;
      case $(this).hasClass('class3'):
        // do stuff
        break;
    }
}


回答3:

I think the cleanest way might just be this:

$('.myclass a.class1').click(function() {
   // code to process class1
});

$('.myclass a.class2').click(function() {
   // code to process class2
});

$('.myclass a.class3').click(function() {
   // code to process class3
});

$('.myclass a.class4').click(function() {
   // code to process class4
});

If you had a zillion of them, you could even put them in a data structure like this:

// to define them all
var classHandlers = {
    class1: function() {
        // class1 code here
    },
    class2: function() {
        // class2 code here
    },
    class3: function() {
        // class3 code here
    },
    class4: function() {
        // class4 code here
    }
};

// to register them all
$.each(classHandlers, function(key, fn) {
    $('.myclass a.' + key).click(fn);
});

Since you've asked (in a comment) how you would do an event handler for the objects with no class name, here's how you could do that if you were looking for no class name:

$(".myclass a").not("[class]").click(function() {
    // code to handle objects with no class name here
});

I tested it out here: http://jsfiddle.net/jfriend00/TAjKR/



回答4:

I do not think that a single switch statement will help here, because one element can have multiple classes, and you cannot use elem.className to switch. An option is to structure the code in a more readable way, using a for statement in which to have switches...:

$('.myclass a').click(function() 
{
    var classes = ["class1", "class2", "class3","class4"];
    var self = $(this);
    for(var i =0, ii = classes.length;i<ii;i++)
    {
        var className = classes[i];
        if(self.hasClass(className))
        {
            switch(className)
            {
                case 'class1':
                    //code here... 
                break;
                case 'class2':
                    //code here... 
                break;      
                case 'class3':
                    //code here... 
                break;     
                case 'class4':
                    //code here... 
                break;
            }

        }
    }       
});


回答5:

To check hasClass in an switch statement:

var elementClass;
var classCheck = $('#myElement').hasClass(elementClass)

switch(classCheck){
  case elementClass === 'foo':
     console.log('whatever');
     break;
}


回答6:

I know this is late and your user only has one class, but, if there was more than one class:

//<div class="foo bar"></div>
//<div class="other bar"></div>

switch(true) {
  case 'foo':
    true;
    break;
  case 'other':
    true;
}


回答7:

    $("#isTest").click(function () {

	  if($('div').is('.redColor')){
	  	$('div').addClass('blueColor');
	  }

    });

    $("#hasClassTest").click(function () {

	  if($('div').hasClass('.redColor')){
	  	$('div').addClass('blueColor');
	  }

    });

	$("#reset").click(function () {
	  location.reload();
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<style type="text/css">
  .redColor {
  	background:red;
  }
  .blueColor {
  	background:blue;
  }
 </style>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>
  <h1>jQuery check if an element has a certain class</h1>

  <div class="redColor">This is a div tag with class name of "redColor"</div>

  <p>
  <button id="isTest">is('.redColor')</button>
  <button id="hasClassTest">hasClass('.redColor')</button>
  <button id="reset">reset</button>
  </p>

</body>
</html>