jQuery Switch Case插件? [英] jQuery Switch Case Plugin?
问题描述
我知道switch case语句是javascript固有的,您无法更改.我仍在学习javascript和jQuery,所以我可以通过,但我不知道该写些与jQuery本身差不多的东西.因此,将其作为一个想法或关于这个想法是否可行的问题.
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;
}
甚至像这样的事情也会很好(可能是一个更合理的主意)...
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;
}
推荐答案
通常,开关并不是解决问题的最佳方法,但是使用jQuery,您可以制作一个类似于switch语句的插件:
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);
您将像这样使用插件:
$(this).switchClasses(
{
"class1":
function(class) {
// Do something for this class,
// the "this" variable is the jquery object that matched the class
},
"class2":
function(class) {
}
}
);
这篇关于jQuery Switch Case插件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!