2017-04-25 93 views
0

我在我的選擇選項腳本中有一些問題,但我不明白,什麼是錯的?對不起,我不是真正的jQuery專家。做一些選擇開關

HTML

<fieldset> 
<select id="sorting"> 
    <option value="1">A-Z</option> 
    <option value="2">Number</option> 
</select> 
</fieldset> 

jQuery的

$(document).change(function() { 
    if($("#sorting").prop("selectedIndex", 1)) { 
     alert("A-Z"); 
    } 
    else if($("#sorting").prop("selectedIndex", 2)) { 
     alert("Number"); 
    }   
}); 

我的問題:它總是 「AZ」,我不能切換到 「數字」 選擇號碼;(

這裏是我的fiddle

+0

非常簡單 - > https://jsfiddle.net/bymfjrfk/1/ – adeneo

回答

4

使用.val()獲取選擇的值:

$("#sorting").change(function() { 
 
    if ($(this).val() == 1) { 
 
    alert("A-Z"); 
 
    } else if ($(this).val() == 2) { 
 
    alert("Number"); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<fieldset> 
 
    <select id="sorting"> 
 
    <option value="1">A-Z</option> 
 
    <option value="2">Number</option> 
 
    </select> 
 
</fieldset>

+1

啊,好的,非常感謝!很棒。 – Pepe

2

要設置沒有得到所選擇的指數,但指數也是零基礎

更改爲:

$(document).on('change','#sorting', function() { 
    var selectedIndex = this.selectedIndex; 
    if(selectedIndex === 0) { 
     alert("A-Z"); 
    } 
    else if(selectedIndex === 1) { 
     alert("Number"); 
    }   
}); 
+0

哎,該死的,這很有道理!謝謝! – Pepe

+0

我選擇j08691解決方案,因爲它有點更聰明,但我投票支持你的版本,因爲你可以幫我找到腳本版本的失敗 - 所以也要謝謝! – Pepe

0

你在設定 HTML屬性,因此在jQuery中使用.val()以獲取期權的價值。