简体   繁体   中英

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. 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.

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"

The script should be within the body element at the end of ending tag, it is the best practice. If you would put the ''script within head element, it would load the javascript before the content. -The Best practice is to load it after the content is loaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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