简体   繁体   English

为什么 console.log 不使用 VS Code 在控制台中显示结果?

[英]Why doesn't console.log show the result in the console using VS Code?

If I use codepen, the code works and shows the calculated result in the console.如果我使用 codepen,代码可以工作并在控制台中显示计算结果。 If I use visual studio code, and view the page using the live server, or open index.html manually, I get the error "ReferenceError: calc() is not defined" when I click calculate.如果我使用 Visual Studio 代码,并使用实时服务器查看页面,或手动打开 index.html,我在单击计算时收到错误“ReferenceError: calc() is not defined”。

Why is this?为什么是这样?

Edited to add - script has been moved inside the body but the code still doesn't work.编辑添加 - 脚本已在正文中移动,但代码仍然不起作用。

enter image description here在此处输入图像描述

 function calc() { var a = parseInt(document.querySelector('#value1').value); var b = parseInt(document.querySelector('#value2').value); var op = document.querySelector('#operator').value; var calculate; if (op == 'add') { calculate = a + b; } else if (op == 'min') { calculate = a - b; } else if (op == 'div') { calculate = a / b; } else if (op == 'mul') { calculate = a * b; } console.log(calculate); }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1:0"> <title>Calculator</title> </head> <body> <form> Value 1: <input type="text" id="value1"> Value 2: <input type="text" id="value2"> Operator. <select id="operator"> <option value="add">Add</option> <option value="min">Minus</option> <option value="div">Divide</option> <option value="mul">Multiply</option> </select> <button type="button" onclick="calc()">Calculate</button> </form> </body> <script scr="app.js"></script> </html>

Spelling mistake - "src" not "scr"拼写错误——“src”不是“scr”

The script should be within the body element at the end of ending tag, it is the best practice.脚本应该在结束标记末尾的 body 元素内,这是最佳实践。 If you would put the ''script within head element, it would load the javascript before the content.如果您将''脚本放在 head 元素中,它将在内容之前加载 javascript。 -The Best practice is to load it after the content is loaded. - 最佳做法是在加载内容后加载它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM