javascript - Jquery 与纯 javascript,为什么我的代码不起作用?
问题描述
我是 Javascript 新手,遇到了一个我无法解决的问题。我想用 jquery 将一个示例重写为纯 Javascript。
我不明白为什么这不起作用。为什么函数外的变量“vorlauf”为空?不是全局变量吗?我附上了控制台输出的图片。
没有按预期工作(试图省略每一个混乱......):
<!DOCTYPE HTML>
<html>
<head>
<script>
let vorlauf = new Array();
let getJSON = function (name) {
fetch(name + ".json")
.then(response => response.json())
.then(parsed => {
console.log(parsed.length, parsed)
for (let i = 0; i < parsed.length; i++) {
vorlauf.push({
x: new Date(parsed[i].date + " " + parsed[i].time),
y: Number(parsed[i].temp) / 1000
})
}
});
}
getJSON("vorlauf")
console.log("Nach Aufruf getJSON " + vorlauf.length)
</script>
</head>
<body>
</body>
</html>
按预期工作(包括所有内容):
!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function() {
let vorlauf = [];
let chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title: {
text: "Vorlauf"
},
axisY: {
title: "Grad",
titleFontSize: 24
},
axisX:{
valueFormatString: "YYYY-MM-DD hh:mm:ss" ,
labelAngle: -50
},
data: [{
name: "Vorlauf",
showInLegend: true,
type: "spline",
dataPoints: vorlauf
}]
});
$.getJSON("http://localhost/vorlauf.json", function(data) {
for(let i = 0; i < data.length; i++) {
vorlauf.push({
x: new Date(data[i].date + " " + data[i].time),
y: Number(data[i].temp) / 1000
});
}
chart.render();
})
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 70%; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
json数据:
[{"date": "2020-02-22", "temp": "39937", "time": "09:28:59"}, {"date": "2020-02-22", "temp": "39937", "time": "09:29:21"}]
解决方案
请把所有的javascript放在上面。
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div id="chartContainer" style="height: 70%; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script>
window.onload = function() {
let vorlauf = [];
let chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title: {
text: "Vorlauf"
},
axisY: {
title: "Grad",
titleFontSize: 24
},
axisX: {
valueFormatString: "YYYY-MM-DD hh:mm:ss",
labelAngle: -50
},
data: [{
name: "Vorlauf",
showInLegend: true,
type: "spline",
dataPoints: vorlauf
}]
});
$.getJSON("http://localhost/vorlauf.json", function(data) {
for (let i = 0; i < data.length; i++) {
vorlauf.push({
x: new Date(data[i].date + " " + data[i].time),
y: Number(data[i].temp) / 1000
});
}
chart.render();
})
}
</script>
推荐阅读
- c - long int 中 cpp 的分段错误高于 999999
- json - 可能将 JSONObject 转换为 java 字符串
- c# - 将 C# 类属性转换为 XML 属性
- javascript - Javascript 事件委托/冒泡
- javascript - 如何从对象中的对象数组中更新对象?
- python - GRID_SEARCH 当需要一维数组时,传递了列向量 y
- javascript - 尽管满足条件,但 For 循环中的 IF 语句未执行
- python - Python heapq 实现
- python - 在 for 循环之外更改变量
- c++ - 将整数更改为长整数时出现大数字的浮点异常和不准确的结果