在JS中
var vehicleData = [{year: 2015, make: "Audi", model: "A4"},
{year: 2014, make: "Benz", model: "c2000"},
{year: 2015, make: "Maruti", model: "s-cross"},
{year: 2015, make: "Maruti", model: "WagonR"}
];
var uniqueNames=[];
for(var i = 0; i<vehicleData.length; i++){
buildDropdownYear(i);
}
function buildDropdownYear(n) {
var yearSelect = document.getElementById("selectMe");
var drop1 = document.createElement("option");
var carYear = buildCtrl(n, uniqueNames,"option");
yearSelect.appendChild(carYear);
}
function buildCtrl(n, data, ctrl){
for(var i = 0; i< vehicleData.length; i++){
if(uniqueNames.indexOf(vehicleData[i].year) === -1){
uniqueNames.push(vehicleData[i].year);
}
}
for(i = 0; i< uniqueNames.length; i++){
console.log(uniqueNames[i]);
}
var item = document.createElement(ctrl);
if(data){
item.innerHTML = data[n];
}
return item;
}
输出后,undefined将进入下拉列表。我想从年份部分[来自json数据]的下拉列表中获得唯一值。
我的plunker代码是:http://plnkr.co/edit/fMufqCctzHe4Umbpu6Ag?p=preview
答案 0 :(得分:0)
这里有几个问题,一旦你开始制作其他下拉菜单,情况会变得更糟,你应该总是尽可能地抽象出来,这样你就可以反复使用你的功能:
这可以在一个函数中执行您想要的操作:NEW PLUNKER
var vehicleData = [{year: 2015, make: "Audi", model: "A4"},
{year: 2014, make: "Benz", model: "c2000"},
{year: 2016, make: "Maruti", model: "s-cross"},
{year: 2015, make: "Maruti", model: "WagonR"}
];
function buildDD(id){
var selector = document.getElementById(id);
var newDataArray = vehicleData.map(function(d) {
return d[id]
})
var uniques = newDataArray.reduce(function(a, b) {
if (a.indexOf(b) === -1) {
a.push(b);
}
return a;
}, []);
uniques.forEach(function(el) {
var opt = document.createElement('option');
opt.innerHTML = el;
selector.appendChild(opt)
})
return newDataArray;
}
buildDD('year')
buildDD('make')
buildDD('model')