I know the switch case statement is inherent to javascript and you can't change it. I'm still learning javascript and jQuery so I can get by, but I don't know enough to write something that might be on the level of jQuery itself. So, take this as an idea or a question about if this idea is feasible.
This is my idea, a switch case statement that can use objects... which can be used something like this:
switch( $(this) ){
case .hasClass('foo'):
// do something
break;
case .filter('.bar').attr('id') == 'foo':
// do something else
break;
}
Edit: Even something like this would be nice (possibly a more reasonable idea)...
switch ($(this).hasClass()) {
case 'foo':
alert('found a foo!');
break;
case 'bar':
alert('found a bar!');
break;
}
Often switches are not the best way to solve a problem, but using jQuery you could make a plugin that works kind of like a switch statement:
(function($) {
$.fn.switchClasses = function(switches) {
return this.each(function() {
var that = this;
$.each(this.attr("class").split(' '), function(i, class) {
var func = switches[class];
if(func)
func.apply(that, class);
});
});
};
})(jQuery);
You would use the plugin like so:
$(this).switchClasses(
{
"class1":
function(class) {
// Do something for this class,
// the "this" variable is the jquery object that matched the class
},
"class2":
function(class) {
}
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With