JQuery从JS数组填充菜单而不重复

JQuery从JS数组填充菜单而不重复,jquery,arrays,menu,append,populate,Jquery,Arrays,Menu,Append,Populate,我有一个问题,大约两天都无法解决。 我有一个带分隔符的字符串,我想通过JQuery填充菜单。 我的阵型是这样的 Country1,City1|Country1,City2|Country2,City1|Country3,City1|Country3,City2|Country3,City3 Country1,City1 | Country1,City2 | Country2,City1 | Country3,City1 | Country3,City2 | Country3,City3 我想通过

我有一个问题,大约两天都无法解决。
我有一个带分隔符的字符串,我想通过JQuery填充菜单。
我的阵型是这样的

Country1,City1|Country1,City2|Country2,City1|Country3,City1|Country3,City2|Country3,City3 Country1,City1 | Country1,City2 | Country2,City1 | Country3,City1 | Country3,City2 | Country3,City3
我想通过使用JQuery
append
函数(或任何其他建议的方式)来使用菜单结构
我的意思是,当用户将鼠标悬停在我的菜单上时,会弹出一个菜单,显示所有国家,每个国家都有自己的子菜单元素(城市)。
我想指出,有多少国家存在,每个国家有多少城市是未知的。
我使用了
unique
功能来消除重复的国家,但我不能将城市放入国家。

现在就感谢您。

请参阅此工作示例:

首先需要在一个对象中收集每个国家的城市,并将国家名称作为关键字,然后遍历该对象以创建列表:

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);
});
var data=“国家1,城市1 |国家1,城市2 |国家2,城市1 |国家3,城市1 |国家3,城市2 |国家3,城市3”;
//分成国家/城市对
data=data.split(“|”);
var国家={},
对,国家,城市;

对于(var x=0;x您的数组应该是如下所示的多维数组:

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>
var选项=”;
foreach(国家作为国家)
{
foreach(国家作为城市)
{
选项+=“”+城市+“”;
}
}
$(“#cities”).html(选项)

您的数组实际上是管道分隔的字符串还是真实数组?@nrabinowitz很抱歉它还不是数组:)管道分隔的stringjQuery.unique()对字符串或数字数组不起作用。@mblase75我尝试拆分此字符串并将国家作为数组,然后使用unique函数删除重复的国家(我成功)但我不能把城市放在国家上。这基本上与nRabinowitz建议的解决方案相同,只是你的对象值应该是数组,而不是子对象,对吗?这有实际意义吗?首先,你的代码语法不正确-
{city1,city2}
是Javascript中的语法错误。迭代数组通常也比较容易。建议指出,我唯一想说的是他要了一个选择框,你看到上面的问题了吗?值得一提的是:--相同的循环,不同的HTML构建。我不喜欢使用
$。当一个普通的
for
循环可以使用时,每个
都可以。好吧,我一直被告知(主要是由jslint:)你需要用一个条件
if(y.hasOwnProperty(x))
语句包装
for(x in y)
循环。这对我来说总是很痛苦。我还喜欢
的内部函数each()
提供的范围控制。但这实际上只是个人喜好添加一些未请求的国家/地区和城市排序。遗憾的是,
Object.keys
没有得到普遍支持,因此需要一个额外的数组。@mblase75,城市列表应该被扭曲为国家列表元素,但在您的小提琴中,它们是自我扭曲的。如何更正此问题?我的意思是应该是这样的