2012-08-31 38 views
0

我發現這裏的另一個線程下面的代碼來創建一個jQuery下拉菜單:jQuery的下拉菜單不加載內容選擇性

$(document).ready(function() { 
    $('#myselector').change(function(){ 
     $('.statecontent').hide(); 
     $('#' + $(this).val()).show();  
    }); 
}); 

HTML看起來像這樣

<select id="myselector"> 
    <option value="state1">State 1</option> 
    <option value="state2">State 2 </option> 
    <option value="state3">State 3</option> 
</select> 

<div id="state1" class="statecontent">State1 Specific Page Content Goes here</div> 
<div id="state2" class="statecontent">State2 Specific Page Content Goes here</div> 
<div id="state3" class="statecontent">State3 Specific Page Content Goes here</div> 

這個工程除了就好一個問題:當頁面加載時,它顯示所有三個選項的文本。但是,一旦選擇了選項,其他文本就會消失,只會顯示相關文本。爲什麼加載所有三個選項的文本?我如何解決這個問題,直到用戶選擇另一個選項才顯示第一個選項的文本?先謝謝您的幫助。

回答

1
$(document).ready(function() { 
    // this is for the case an option comes selected from server 
    showRelatedDiv(); 

    $('#myselector').change(function(){ 
     showRelatedDiv(); 
    }); 
}); 

function showRelatedDiv(){ 
    $('.statecontent').hide(); 
    $('#' + $('#myselector').val()).show();   
} 
1

只是觸發更改事件在頁面加載,就像這樣:

$(function() { 
    $('#myselector').on('change', function(){ 
     $('#' + this.value).show().siblings('.statecontent').hide();  
    }).change(); 
});​ 

FIDDLE

+0

+1最佳答案至今 –

0

你需要一次頁面加載執行一些處理。您的篩選僅在發生更改事件時啓動。

$(document).ready(function() { 
    //Hide all states on load 
    $('.statecontent').hide(); 
    //Determine which state is selected and show 
    $('#' + $('#myselector').val()).show(); 

    //Bind the change event. 
    $('#myselector').change(function(){ 
     $('.statecontent').hide(); 
     $('#' + $(this).val()).show();  
    }); 
}); 

工作實例:http://jsfiddle.net/7cEXZ/

1

你可以試試這個:

$(document).ready(function() { 

    $('.statecontent').hide(); 
    $('#' + $('#myselector').val()).show(); 
    $('#myselector').change(function(){ 
     $('.statecontent').hide(); 
     $('#' + $(this).val()).show();  
    }); 
}); 

這裏是工作fiddle