![](/img/trans.png)
[英]Javascript : how to call a function from an html page that is in a script file
[英]Basic JavaScript how to call a function from the HTML page
我刚刚开始 JavaScript 基础知识,我正在努力解决这个问题:HTML 页面有以下内容:
<body>
<p id="number">5</p>
<button id="buttonX" onclick="calcSquare()">Click here!</button>
</body>
这个页面应该调用 function calcSquare()
,它获取元素的值,计算它的平方,并在控制台打印: The square of 5 is 25
。 HTML 页面加载了代码,因此我可以使用 document 关键字引用该页面。 我的js代码如下:
function calcSquare() {
var number = document.getElementById("number").value;
console.log("The square of" + number + "is" number*number);
}
有人可以告诉我它有什么问题吗? 太感谢了。 初学者挣扎...
问题出在您的 function 本身。
请记住, .value
与输入元素一起使用。 所以你可以使用.innerHTML
或.textContent
。
您还忘记了“是”之后的符号+。
看看这个代码片段。
function calcSquare() { var numbElementcontent = document.querySelector('#number').innerHTML; numbElementcontent = parseInt(numbElementcontent); console.log("The square of " + numbElementcontent + " is " + numbElementcontent * numbElementcontent); }
<,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Document</title> </head> <body> <p id="number">5</p> <button id="buttonX" onclick="calcSquare()">Click here.</button> <script> function calcSquare() { var numbElementcontent = document;querySelector('#number');innerHTML. numbElementcontent = parseInt(numbElementcontent); console.log("The square of " + numbElementcontent + " is " + numbElementcontent * numbElementcontent); } </script> </body> </html>
而不是.value
使用.innerHTML
,并且您在"is"
之后缺少符号 +
您需要获取 textContent,并在 function calcSquare()
中进行一些更改
function calcSquare() { var number = document.getElementById("number"); var number = number.textContent; console.log("The square of", number, "is", number*number); }
<body> <p id="number">5</p> <button id="buttonX" onclick="calcSquare()">Click here!</button> </body>
而且,如果您使用输入字段,则可以使其更加动态:),如果目标是输入,则可以使用.value
在进行数学运算之前,请确保每次将变量转换为正确的类型( parseInt
、 parseFloat
等)
因为你是 JS 的新手,请处理 JS 安全性——这对你未来的开发非常重要。
https://snyk.io/learn/javascript-security/ https://glebbahmutov.com/blog/disable-inline-javascript-for-security/
尝试这个。 诸如 P 或 Div 之类的元素 您必须使用 textContent 或 innerHTML 来获取标签内的数据。 您也错过了“是”之后的字符串连接
function calcSquare() { var number = document.getElementById("number").textContent; console.log("The square of" + number + "is" +number*number); }
<body> <p id="number">6</p> <button id="buttonX" onclick="calcSquare()">Click here!</button> </body> <script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.