我只是一個初學者,我想找到這個問題的答案。
這是我的html代碼。
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type = "text" name = "step" id = "step">
<button onclick="myFunction()">Submit</button>
<p id = "demo"></p>
</body>
</html>
這是我的 JavaScript 代碼。
var step = document.getElementById("step").innerHTML;
parseInt(step);
function matchHouses(step) {
var num = 0;
var one = 1;
while (num != step){
one = 5;
num ;
}
return one;
}
function myFunction(){
document.getElementById("demo").innerHTML = matchHouses(step);
}
我所做的是通過單擊按鈕呼叫函式 matchHouses(step) 。但輸出始終為 1。我還將 parseInt 放入步驟 id,因為它是字串,但它仍然不起作用。如果輸入為 1,我期望輸出為 1 5,如果輸入為 2,則為 1 5 5,依此類推。我如何使它作業?
uj5u.com熱心網友回復:
兩個關鍵的事情是 a)parseInt不會“就地”進行評估。它要么需要分配給一個變數,要么需要在您將其傳遞給matchHouse函式時完成評估,并且b)您應該獲得value輸入元素的,而不是innerHTML.
以下是一些附加說明:
首先快取所有元素。
在 JavaScript 中添加事件偵聽器,而不是在 HTML 中使用行內 JS。
不需要有一個額外的變數來計數 - 只需遞減
step直到它達到零。Number可能是parseInt需要基數才能正常作業的更合適的替代方案。如果您忽略它,它并不總是默認為 10 為底。將呼叫函式的結果分配給
demo'stextContent(不是innerHTML因為它只是一個簡單的字串,也不是 HTML 標記的字串。
// Cache elements
const step = document.querySelector('#step');
const demo = document.querySelector('#demo');
const button = document.querySelector('button');
// Add a listener to the button
button.addEventListener('click', handleClick);
function matchHouses(step) {
let out = 1;
while (step > 0) {
out = 5;
--step;
}
return out;
}
function handleClick() {
// Get the value of the input string and
// coerce it to a number
const n = Number(step.value);
demo.textContent = matchHouses(n);
}
<body>
<input type="text" name="step" id="step">
<button type="button">Submit</button>
<p id="demo"></p>
</body>
uj5u.com熱心網友回復:
我像這樣重寫了你的代碼:
let step = 0;
function handleInput(e){
step = e.value;
}
function matchHouses(step) {
var num = 0;
var one = 1;
while (num != step){
one = 5;
num ;
}
return one;
}
function myFunction(){
document.getElementById("demo").innerHTML = matchHouses(step);
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type = "text" name="step" id="step" onkeyup='handleInput(this)'>
<button onclick="myFunction()">Submit</button>
<p id = "demo"></p>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/532731.html
