2009-10-24 44 views
3

我知道switch case語句是javascript固有的,你不能改變它。我仍在學習JavaScript和jQuery,所以我可以通過,但我不知道寫什麼可能是jQuery本身的水平。所以,把這看作是一個想法或問題,如果這個想法是可行的。jQuery Switch Case插件?

這是我的想法,能夠使用對象可以使用這樣的一個開關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; 

} 
+0

這是爲什麼社會維基? – cdmckay

+1

*聳肩*似乎是正確的做法? – Mottie

+0

大聲笑,現在我已經有一段時間來思考這個問題 - 我已經包含了第二個更合理的例子。另外,我將此作爲社區wiki,因爲可能永遠無法回答這個問題。看看其他人是否會覺得這很有用,這更是一個想法。 – Mottie

回答

3

經常開關不解決問題的最好辦法,但使用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) { 

     } 
    } 
); 
+1

我一直喜歡使用對象文字作爲快速切換語句。 +1 – gnarf

+0

不適合我... – EmRa228

0

正常的if/else有什麼問題?

inst = $(this); 

if (inst.hasClass('foo')) { 
    // do something 
} else if (inst.filter('.bar').attr('id') == 'foo') { 
    // do something else 
} 
+2

超過一個或兩個案例後的可讀性? –

0

如果您正在處理一個類名稱,則可以打開element.attr('class')

如果你處理的不止一個,你可以做element.attr('class').split(/\s+/)並檢查該數組中的類名。

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

你可能想要改變你的方法。我看不出這是做你正在嘗試做的最有效的方式。

1

首先,switch語句只對int的作用。我不知道爲什麼javascript保持C/C++的這種限制,但它在那裏。

使用嵌套的if-then-else塊代替交換機可能會導致難以讀取的代碼,如果您處理的是多個選項。

但是,就像在C和C++中一樣,有一些解決方法,這個涉及到使用「break」就像goto,這並不總是邪惡的。這是一種情況(大量嵌套的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 
0
(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); 

「階級」是保留名稱, 我增加了一些失蹤括號