![](/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.