2012-02-06 190 views
4

如何在選擇默認值時允許我的更改事件發生在我的下拉菜單中?JQuery選擇下拉更改事件 - 選擇默認值

選擇值1爲默認值,但也有變化功能的工作..

<select id='statsGraphingSelect'> 
    <option value='1' selected="selected">1</option> 
    <option value='2'>2</option> 
    <option value='3'>3</option> 
    <option value='4'>4</option> 
</select>  

$("#statsGraphingSelect").change(function() { 
    if ($("#statsGraphingSelect option[value='1']").attr('selected')) {//something happens here } 
    if ($("#statsGraphingSelect option[value='2']").attr('selected')) {//something happens here } 
    if ($("#statsGraphingSelect option[value='3']").attr('selected')) {//something happens here } 
    if ($("#statsGraphingSelect option[value='4']").attr('selected')) {//something happens here } 
} 

回答

16

我不知道什麼是你想實現的,你可以嘗試

$("#statsGraphingSelect").change(function() { 
var n = $(this).val(); 
switch(n) 
{ 
case '1': 
    execute code block 1 
    break; 
case '2': 
    execute code block 2 
    break; 

} 
}); 
現在你給

標記,如果你喜歡觸發

$(function(){ 
$("#statsGraphingSelect").change(); 
}); 

case 1無線就緒處理程序變化將被執行

DEMO

+0

這很有效,謝謝。在用戶引起變化事件之前,最初設置跑步說case 1的情況如何? – user1040259 2012-02-06 23:21:56

+0

@ user1040259查看答案更新 – Rafay 2012-02-06 23:22:25

+0

@ user1040259再次用演示更新了答案,看一看 – Rafay 2012-02-06 23:37:09