在网页中添加表单组件,要求用户输入统计数据,根据用户数据绘制相应的饼状图和柱状图。 1. 要求对用户输入进行有效性验证; 2. 通过点击按钮绘制饼状图或柱状图; 3. 饼状图和柱状图要有数据标注。 请你根据以上条件写一个代码
时间: 2024-10-21 10:17:51 浏览: 57
在网页中添加表单组件并实现统计图表功能,可以使用HTML、JavaScript(如Chart.js库)以及一些轻量级的前端框架,例如React或Vue。下面是一个简单的示例,我们将使用JavaScript和HTML编写,不过实际项目中可能需要结合后端服务处理数据验证:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Statistical Charts</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<form id="dataForm">
<label for="statData">请输入统计数据:</label><br>
<input type="number" id="statData" name="statData" required><br>
<button onclick="drawCharts()">绘制图表</button>
</form>
<div id="pieChartContainer"></div>
<div id="barChartContainer"></div>
<script>
function drawCharts() {
const data = document.getElementById('statData').value;
// 数据验证
if (!isNaN(data)) {
let parsedData = Number(data);
let labels = []; // 标注数组
// 假设数据按逗号分隔,你可以根据需求调整
labels = data.split(',');
// 饼状图
var pieChart = new Chart(document.getElementById('pieChartContainer'), {
type: 'pie',
data: {
labels,
datasets: [{
data: labels.map(Number),
backgroundColor: ['#f4c500', '#FF6384', '#36a2eb'],
}]
},
options: {
tooltips: {
enabled: true,
callbacks: {
label: (tooltipItem) => `${tooltipItem.yLabel}: ${tooltipItem.value}`
}
}
}
});
// 柱状图
var barChart = new Chart(document.getElementById('barChartContainer'), {
type: 'bar',
data: {
labels: labels,
datasets: [{
data: labels.map(Number),
backgroundColor: ['#f4c500', '#FF6384', '#36a2eb'],
}]
},
options: {
tooltips: {
enabled: true,
callbacks: {
label: (tooltipItem) => `${tooltipItem.xLabel}: ${tooltipItem.yLabel}`
}
}
}
});
} else {
alert("无效的数据,请输入数字!");
}
}
</script>
</body>
</html>
```
阅读全文
相关推荐


















