jQuery Switch Case插件?

我知道switch case语句是javascript固有的,你无法改变它。 我还在学习javascript和jQuery,所以我可以顺便说一下,但是我不知道写一些可能在jQuery本身的东西。 因此,将此作为一个想法或一个问题,如果这个想法是可行的。

这是我的想法,一个可以使用对象的switch case语句……可以使用这样的东西:

switch( $(this) ){ case .hasClass('foo'): // do something break; case .filter('.bar').attr('id') == 'foo': // do something else break; } 

编辑:即使这样的事情也会很好(可能是一个更合理的想法)……

 switch ($(this).hasClass()) { case 'foo': alert('found a foo!'); break; case 'bar': alert('found a bar!'); break; } 

通常,switch不是解决问题的最佳方法,但是使用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) { } } ); 

首先,switch语句仅适用于int。 我不确定为什么javascript在C / C ++中保留了这个限制,但它确实存在。

如果您正在处理多个选项,那么使用嵌套的if-then-else块而不是交换机可能会导致代码难以读取。

然而,就像在C和C ++中一样,有一些解决方法,这个涉及像goto一样使用“break”,这并不总是邪恶的。 这是一种情况(大量的嵌套if-the-else),其中goto会使代码更有效和可读。 在C / C ++中,你可以使用goto实现这一点,标签位于if系列的末尾(现在是开关括号的末尾),并跳过跳转到开关上下文。

 switch (1) { //yes, that is a hardcoded 1, we only want the switch block for the break keyword if (yourString == "Case 1") { do_stuff_1(); break; // well, we're done, let's get out of here. } //implicit else - if you matched the first one, you'd be out of here if (yourString == "Case 2") { do_stuff_2(); break; // well, we're done, let's get out of here. } // etc..... default: do_error_condition(); } //end of switch 

普通if/else什么问题?

 inst = $(this); if (inst.hasClass('foo')) { // do something } else if (inst.filter('.bar').attr('id') == 'foo') { // do something else } 

如果您正在处理一个类名,则可以打开element.attr('class')

如果你正在处理多个,你可以做element.attr('class').split(/\s+/)并检查该数组中的类名。

我也认为你可能想看看.is() 。 你可以做if( element.is('a.foo') ) console.log( 'This is a link with a 'foo' class.' );

您可能想要改变您的方法。 我不认为这是你做你想做的最有效的方式。

  (function($) { $.fn.switchClasses = function(switches) { return this.each(function() { var that = this; $.each(this.attr("class").split(' '), function(i, classname) { var func = switches[classname]; if(func){ func.apply(that, classname); } }); }); }; })(jQuery); 

‘class’是保留名称,我添加了一些缺少的括号