通常情况下,开关不是解决问题的最佳方法,但是使用jquery,您可以创建一个类似switch语句的插件:
(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);
您可以这样使用插件:
$(this).switchClasses(
{
"class1":
function(class) {
// Do something for this class,
// the "this" variable is the jquery object that matched the class
},
"class2":
function(class) {
}
}
);