2011-10-12 42 views
1

我有一個問題,我無法克服大約兩天。
我有一個分隔字符串,我想通過JQuery填充菜單。
我這樣的數組;
從JS陣列填充菜單沒有通過JQuery重複

 
Country1,City1|Country1,City2|Country2,City1|Country3,City1|Country3,City2|Country3,City3 


,我想通過使用JQuery append函數(或任何其他建議的方式)
我的意思是,用this菜單結構時,在我的菜單中的用戶懸停觸發,會彈出菜單和所有國家將被顯示,每個人都有自己的子菜單元素(城市)。
我想指出,有多少個國家存在,每個Contry有多少個城市不爲人知。
我使用unique函數來重複重複的國家,但我並沒有把城市放入國家。
由於現在..

+0

是您的陣列實際上是一個管道分隔的字符串,或真正的數組菜單嗎? – nrabinowitz

+0

@nrabinowitz對不起,它不是數組:)管道分隔字符串 – Alper

+0

jQuery.unique()不適用於字符串或數字的數組。 – Blazemonger

回答

2

見該工作示例:http://jsfiddle.net/nrabinowitz/FDWgF/

首先需要收集每個國家的城市與國家名稱作爲鍵的對象,然後通過該對象進行迭代,以創建清單:

var data = "Country1,City1|Country1,City2|Country2,City1|Country3,City1|Country3,City2|Country3,City3"; 

// split into country/city pairs 
data = data.split('|'); 

var countries = {}, 
    pair, country, city; 

for (var x=0; x<data.length; x++) { 
    // get pair as an array 
    pair = data[x].split(','); 
    country = pair[0]; 
    city = pair[1]; 
    // make sure the country is in our object 
    if (!(country in countries)) { 
     countries[country] = [] 
    } 
    // add the city to the list for that country 
    countries[country].push(city); 
} 

// now get the values out of the object 
$.each(countries, function(country, cities) { 
    var $country = $('<li>' + country + '<ul></ul></li>'); 
    // append each city to sub-list 
    $.each(cities, function(i, city) { 
     $('ul', $country) 
      .append('<li>' + city + '</li>') 
    }); 
    // now append the whole thing to the country list 
    $('#countries').append($country); 
}); 
+1

這是值得的:http://jsfiddle.net/mblase75/FDWgF/1/ - 相同的循環,不同的HTML構建。當一個簡單的''''''循環會做時,我不喜歡使用'$ .each'。 – Blazemonger

+0

非常感謝你......它工作完美.. – Alper

+0

嗯,我總是被告知(主要是jslint :)你需要用'if(y。 hasOwnProperty(x))'語句。這對我來說總是很痛苦。我也喜歡範圍控制'.each()'提供的內部函數。但這實際上只是個人偏好。 – nrabinowitz

0

你的陣列應該是一個多維數組是這樣的:

var countries = { 
"country1":["city1", "city2"], 
"country2":["city1"], 
"counrty3":["city2", "city2"] 
}; 

然後,你將不會有重複的國家,那麼你應該循環通過與for in數組並填充方式

var options = ""; 
foreach(countries as country) 
{ 
    foreach(country as city) 
    { 
     options += "<option value=" + city+ ">"+ city+ "</options>"; 
    } 
} 
$("#cities").html(options) 
<select id="cities"> 
</select> 
+0

這基本上是由nrabinowitz – Tules

+0

建議相同的解決方案除了你的對象值應該是數組,也不分對象,對不對? – nrabinowitz

+0

它有什麼實際的區別? – Tules