2012-07-20 90 views
0

希望在這裏的任何幫助新手。我有一個簡單的if/else if語句,出於某種原因只能達到第二個條件,即使第三個條件滿足。我已經嘗試添加到最後,嘗試幾乎一切,但仍然沒有。我知道這不起作用,因爲我添加了警報觸發器,並且不管它從未達到第三個條件。我在這裏錯過了什麼?我環顧四周,所以我很抱歉,如果我在這裏擊敗死馬,但我找不到解決方案。我應該注意到,我試圖通過選擇下拉框來改變條件。謝謝!!!如果其他語句不按預期工作

我的代碼:

$('#table_two select:eq(6)').change(function(e){ 

var allDiv = $('#table_two,#table_three,#table_four'); 
var parBoxOne = $('#par_one').val(); 

var totalOne = 1 - parBoxOne; 
var totalTwo = 2 - parBoxOne; 


if ($(this).val() == "made_shot"){ 
$(allDiv).hide(); 
$('#score_one').val(totalOne); 
$('#score_total').val($('.score_input').val()); 
alert('ACE!!'); 
} 

else if ($(this).val() == 'green', 'trees', 'fairway', 'rough', 'sand'){ 
$('#score_one').val(totalOne); 
$('#score_total').val($('.score_input').val()); 
$('#table_two').hide(); 
$('#butt_two').html('Show stroke'); 
alert('triggered two'); 
} 

else if ($(this).val() == 'other', 'penalty_water', 'penalty_ob', 'penalty_sand'){ 
$('#score_one').val(totalTwo); 
$('#score_total').val($('.score_input').val()); 
$('#table_two').hide(); 
alert('triggered three'); 
} 

}); 

回答

1

只是另一個apporoach:

switch($(this).val()){ 
    case 'made_shot': 
     $(allDiv).hide(); 
     $('#score_one').val(totalOne); 
     $('#score_total').val($('.score_input').val()); 
     alert('ACE!!'); 
     break; 

    case 'green': 
    case 'trees': 
    case 'fairway': 
    case 'rough': 
    case 'sand': 
     $('#score_one').val(totalOne); 
     $('#score_total').val($('.score_input').val()); 
     $('#table_two').hide(); 
     $('#butt_two').html('Show stroke'); 
     alert('triggered two'); 
     break; 

    case 'other': 
    case 'penalty_water': 
    case 'penalty_ob': 
    case 'penalty_sand': 
     $('#score_one').val(totalTwo); 
     $('#score_total').val($('.score_input').val()); 
     $('#table_two').hide(); 
     alert('triggered three'); 
     break; 
    } 
+0

+1。其他答案解釋了爲什麼原文不起作用,但當所有條件都測試相同的值時,轉換語句更有意義。 – nnnnnn 2012-07-20 01:24:53

+0

@nnnnnn謝謝你,其他的答案已經解釋了他會出錯的地方。 – sabithpocker 2012-07-20 01:27:17

+0

它的工作原理!感謝您花時間向像我這樣的新手解釋這一點。我很感激! – beatmusic67 2012-07-20 19:12:44

0

你不能比比字符串以這種方式,你可以使用$.inArray()功能 ,而不是創造價值的數組:

jQuery.inArray(值,數組[,fromIndex])

if($.inArray($(this).val(), ['green', 'trees', 'fairway', 'rough', 'sand']) != -1) { 

} 
+0

非常感謝! – beatmusic67 2012-07-20 19:14:25

5

你不能在if using語句逗號多個條件:

if ($(this).val() == 'green', 'trees', 'fairway', 'rough', 'sand')

相反,可以使值列表到一個數組中,並檢查你的價值是數組中:

var stuff = ['green', 'trees', 'fairway', 'rough', 'sand']; 
if ($.inArray($(this).val(), stuff) >= 0) 

要在組合多個條件如果,語法是本(遠長於以上):

if ($(this).val() == 'green' || $(this).val() == 'trees' || ...) 
+0

@raminson對不起,錯字。感謝您指出錯誤 – nbrooks 2012-07-20 01:14:14

+0

謝謝!我很感激。 – beatmusic67 2012-07-20 19:08:41

+0

@ beatmusic67沒問題,很樂意幫忙。如果此(或任何其他)答案有幫助,請點擊左側的複選標記(在投票計數下)將其「接受」爲綠色。你只能接受一個答案,所以接受你最好的幫助。 – nbrooks 2012-07-20 22:06:49