【发布时间】:2021-11-26 06:43:15
【问题描述】:
我是 HTML 和 javascript 的新手。我正在尝试用我的数据文件填充下拉列表并做一个饼图。我的 js 数据如下所示:
const businessData =
[ { '\ufeffbusiness_id': 'y2gFcAVBXmVxFXAugRe5ig'
, name : 'Scrumptious Crumpets'
, address : '7414 SE Milwaukie Ave'
, city : 'Portland'
, state : 'OR'
, latitude : '45.47107'
, longitude : '-122.64827'
, stars : '5'
, review_count : '23'
, is_open : '0'
, category : 'Coffee & Tea'
, attr_key : 'restaurantspricerange2'
, attr_value : '1'
}
这是我的下拉列表:
// render dropdown
const dropdownElement = document.getElementById("state-dropdown");
// states
let states = [
{ name: 'OREGON', abbreviation: 'OR'},
{ name: 'FLORIDA', abbreviation: 'FL'},
{ name: 'OHIO', abbreviation: 'OH'},
{ name: 'MASSACHUSETTS', abbreviation: 'MA'},
{ name: 'TEXAS', abbreviation: 'TX'},
{ name: 'COLORADO', abbreviation: 'CO'},
{ name: 'GEORGIA', abbreviation: 'GA'},
{ name: 'WASHINGTON', abbreviation: 'WA'},
{ name: 'MINNESOTA', abbreviation: 'MN'},
]
// create dropdown item
// <option value="CA">Open this select menu</option>
states.forEach(function(state) {
//create the dropdown items
const optionElement = document.createElement("option");
//add dropdown value (we will use for code)
optionElement.value = state.abbreviation
//create the text that user can read
const node = document.createTextNode(state.name);
optionElement.appendChild(node);
// append to the dropdown select
dropdownElement.appendChild(optionElement)
})
我想创建一个下拉菜单,允许我从多个状态中选择数据并绘制来自该状态的数据。到目前为止,我只能通过一次硬编码一个状态来使图表工作。
我怎样才能将数据提取到我的下拉列表中,这样它就可以... 如果选择 CA,则显示 CA 饼图。如果选择 OR,则显示 OR 饼图等...
const californiaStars = businessData.filter(function (obj) {
return obj.state === 'OR';
//Hard coding here in order to get my graph to work for state of OR only
})
let countOfFiveStars = 0
let countOfFourStars = 0
let countOfThreeStars = 0
let countOfTwoStars = 0
let countOfOneStar = 0
californiaStars.forEach(function(obj) {
switch (obj.stars) {
case "5":
countOfFiveStars++;
break;
case "4":
countOfFourStars++;
break;
case "3":
countOfThreeStars++;
break;
case "2":
countOfTwoStars++;
break;
case "1":
countOfOneStar++;
break;
default: break;
}
})
console.log(californiaStars)
console.log(countOfFiveStars, countOfFourStars, countOfThreeStars, countOfTwoStars, countOfOneStar)
// 3. put into graph (Pie Chart)
var options = {
series: [
countOfFiveStars, countOfFourStars, countOfThreeStars, countOfTwoStars, countOfOneStar
],
chart: {
width: 700,
type: 'pie',
},
labels: ['Five stars', 'Four stars', 'Three stars', 'Two stars', 'One star'],
responsive: [{
breakpoint: 480,
options: {
chart: {
width: 200
},
legend: {
position: 'bottom'
}
}
}]
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
【问题讨论】:
-
听起来您可能想为 Select 添加一个 onChange 处理程序,并在该更改事件中,将每个选定状态推送到一个可以为您的饼图过滤的数组中。
标签: javascript html json html-select