我正在尝试在弹出的模式窗口上显示条形图。我设法使模式可以与按钮一起使用,但该图不会出现。
模式和按钮:
<button id = 'btn' class= 'button'>
Data
</button>
<div id = "myModal" class="modal">
<div class="modalContent">
<span class = "close"> × </span>
<canvas id="myChart"></canvas>
</div>
</div>
</body>
Chart.js:
function renderChart(data, labels) {
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [
"GFA","GBA","NSA","FSR","Open Space Ratio","Sunlight Ratio","Ventilation Ratio","Stories"
],
datasets: [{
label: labels,
data: [ 2.6, 30.6, 5.6, 6.4, 8.7, 2.1, 3.5, 9],
borderColor: 'rgba(75, 192, 192, 0.2)',
backgroundColor: 'rgba(75, 192, 192, 1)',
}]
},
});
}
模式:
var modal = document.getElementById("myModal");
var btn = document.getElementById("btn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function () {
//modal.style.display = 'block'
renderChart(data, labels);
}
span.onclick = function() {
modal.style.display = 'none';
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = 'none';
}
}
我收到错误消息“未捕获的ReferenceError:数据未定义 在“ HTMLButtonElement.btn.onclick”行:“ renderChart(数据,标签);”,但我不确定是什么问题。
我刚开始编写代码,因此,非常感谢您的帮助:)
答案 0 :(得分:0)
我将您的代码带入编辑器,通过它的CDN添加了Chart.js库,错误为data
,(如果删除了labels
,则错误为data
) 。似乎您正在尝试定义data
和labels
,但在函数renderChart()
在不需要或传递给函数的参数的情况下,看起来好像很好地绘制了图表数据!看看我的工作示例:
function renderChart() {
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [
"GFA","GBA","NSA","FSR","Open Space Ratio","Sunlight Ratio","Ventilation Ratio","Stories"
],
datasets: [{
label: this.labels,
data: [ 2.6, 30.6, 5.6, 6.4, 8.7, 2.1, 3.5, 9],
borderColor: 'rgba(75, 192, 192, 0.2)',
backgroundColor: 'rgba(75, 192, 192, 1)',
}]
},
});
}
var modal = document.getElementById("myModal");
var btn = document.getElementById("btn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function () {
modal.style.display = 'block'
renderChart();
}
span.onclick = function() {
modal.style.display = 'none';
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = 'none';
}
}
.modal {
border: 1px solid black;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<body>
<button id = 'btn' class= 'button'>
Data
</button>
<div id = "myModal" class="modal">
<div class="modalContent">
<span class = "close"> × </span>
<canvas id="myChart"></canvas>
</div>
</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
请注意,我还必须将labels
的属性更改为this.labels
,以引用在其已定义的同一对象上的labels
。
希望这可以帮助您步入正轨