javascript - 初学者:那么我在下面的代码中做错了什么?(有吊装的东西??)
问题描述
现在这是一个非常基本的计算器,但正如标题所说,它与提升和声明“var a”有关吗?
<!DOCTYPE html>
<head>
<title>Functions exc. 8</title>
</head>
<body>
Input monthly salary: <input type="text" placeholder="invoer" id="value1"><br>
<button type="button" onclick="calc">Calculate yearly salary</button> <br>
Output yearly salary:<div id="jaarsalaris"></div>
<script>
//calculate the yearly salary
function calc() {
var a = document.getElementById("value1").value;
var calculateMonth = a * 12;
document.getElementById("jaarsalaris").value= calculateMonth;// + berekeningVktgeld;
}
</script>
</body>
</html>
解决方案
有两个问题(以及您可能想要更改的其他几件事),但它们没有提升:
- 你没有调用你的函数。
onclick="calc"
=>onclick="calc()"
。或者更好的是,使用现代事件处理(更多下文)。 div
元素没有value
属性。您可能想分配给textContent
.
还:
- 虽然
a * 12
可行,但由于从字符串到数字的隐式转换,我始终建议将字符串显式转换为数字。(a
是一个字符串,因为您从 an 的value
属性中获取值input
,它始终是一个字符串。)您有很多选择;我会parseFloat
在下面使用。 - 你漏掉了开始
<html>
标签。从技术上讲,如果你有标签,它是可选<head>
的,但我怀疑你把它漏掉了,因为你认为它<!doctype html>
是开始标签。不是,它们是独立的东西(<!doctype html>
是doctype 序言)。
这是一个使用现代事件处理而不是onxyz
-attribute 事件处理程序的示例。这可以让你calc
避免成为全球性的。全局命名空间非常拥挤,很容易产生难以诊断的冲突:
<!DOCTYPE html>
<html>
<head>
<title>Functions exc. 8</title>
</head>
<body>
Input monthly salary: <input type="text" placeholder="invoer" id="value1"><br>
<button id="btn-calc" type="button">Calculate yearly salary</button> <br>
Output yearly salary:<div id="jaarsalaris"></div>
<script>
// This is a "scoping function"
(function() {
document.getElementById("btn-calc").addEventListener("click", calc);
//calculate the yearly salary
function calc() {
var a = parseFloat(document.getElementById("value1").value);
var calculateMonth = a * 12;
document.getElementById("jaarsalaris").textContent = calculateMonth;// + berekeningVktgeld;
}
})();
</script>
</body>
</html>
或者,如果您的环境支持它们(现在大多数都支持),请使用模块:
<!DOCTYPE html>
<html>
<head>
<title>Functions exc. 8</title>
</head>
<body>
Input monthly salary: <input type="text" placeholder="invoer" id="value1"><br>
<button id="btn-calc" type="button">Calculate yearly salary</button> <br>
Output yearly salary:<div id="jaarsalaris"></div>
<script type="module">
document.getElementById("btn-calc").addEventListener("click", calc);
//calculate the yearly salary
function calc() {
var a = parseFloat(document.getElementById("value1").value);
var calculateMonth = a * 12;
document.getElementById("jaarsalaris").value= calculateMonth;// + berekeningVktgeld;
}
</script>
</body>
</html>
模块顶层的代码不在全局范围内(它在模块范围内,只能由模块内的代码访问;模块外的代码不能使用模块内声明的内容,除非它被export
编辑)。
推荐阅读
- vue.js - Quasar 浏览器扩展无法构建,开发工作正常
- php - PHP - 解析 HTML,选择标签,在所选标签内插入另一个 HTML 字符串
- javascript - 有没有办法将动作绑定到不是 Angular 上某个键绑定的每个击键?
- html - 为什么我的页面中的 col-md-6 显示全宽?
- c++ - 删除链表 C++ 中的特定节点
- sql - Apex Oracle calendar When Select list value is null show all and when Select value is not null show filtered
- xpath - 如何单击柏树中跨度类下的链接
- r - 我在尝试连接 R Markdown 中的数据但在非 Markdown 文件中较早工作时遇到错误
- javascript - minmax/1fr 背后的数学原理是什么?
- javascript - 如何将跨度文本转换为输入表单