2013-04-29 39 views
0

我只是想,我的jQuery函數只運行一次。 Currentyl我正在使用國家,州/省下降。所以當用戶選擇任何國家時,它會顯示城市/州。但最初它沒有顯示任何內容,所以我在document.ready上調用它。但問題是,每次展示第一個鄉村城市。那麼有沒有解決方案。或者你可以建議任何其他國家,城市下降。我們如何加載jQuery函數只有一次

守則下拉是

function print_country(country_id){ 
// given the id of the <select> tag as function argument, it inserts <option> tags 
var option_str = document.getElementById(country_id); 
var x, i=0; 
for(x in country_arr){ 
    option_str.options[i++] = new Option(country_arr[x],country_arr[x]); 
} 
} 

function print_state(state_id, state_index){ 
var option_str = document.getElementById(state_id); 
var x, i=0; state_index++; 
var state_arr = s_a[state_index].split("|"); 
for(x in state_arr){ 
     option_str.options[i++] = new Option(state_arr[x],state_arr[x]); 
} 
} 

您還可以修改它,以便在頁面載入的默認第一個國家演出引用。由於

+0

http://underscorejs.org/有一個'once'函數,它的功能,並返回memomizes結果的功能。你可以在這裏看到的來源:http://underscorejs.org/docs/underscore.html#section-66 – asawyer 2013-04-29 13:06:27

回答

0

你應該使用jQuery現在你擁有了它

function print_country(country_id){ 
    // given the id of the <select> tag as function argument, it inserts <option> tags 
    var countrySel = $("#"+country_id); 
    // create a "singleton" by returning if the state exists 
    if (countrySel.size() > 1) return; 
    $.each(country_arr,function() { 
     countrySel.append('<option value="'+$(this)+'">'+$(this)+'</option>'); 
    }); 
    // call it with the second option (assuming "Please select") 
    // change to ,0 for first option 
    print_state("state", 1); 
} 

function print_state(state_id, state_index){ 
    var stateSel = $("#"+state_id); 
    var state_arr = s_a[state_index].split("|"); 
    $.each(state_arr,function() { 
    stateSel.append('<option value="'+$(this)+'">'+$(this)+'</option>'); 
    }); 
} 
+0

Currentyl我使用這個代碼'VAR STATE_ID =的jQuery( '#statecheck')ATTR( 'ID')。 \t print_state_checkbox(STATE_ID,0);' 通過這個時候用戶可以看到的第一個國家的城市,但這個功能顯示第一個國家的每一個國家的時間。 – Adi 2013-04-29 13:28:30

+0

我不明白你每次的意思。請張貼更多的代碼,你的陣列 – mplungjan 2013-04-29 13:32:02

+0

我使用這個[示例](http://bdhacker.wordpress.com/2009/11/21/adding-dropdown-country-state-list-dynamically-into-your-html-形式逐的JavaScript /)。如果您看到演示,則會顯示第一個國家,但它的引用未顯示。我想,國家的城市以及在第一次加載 – Adi 2013-04-29 13:44:22