我正在創建一個網站,并想使用 JavaScript 制作一個工具來根據某人的鞋碼選擇某人的滑板尺寸。這是我正在使用的代碼:
const shoeSize = document.getElementById('shoeSize').value
let boardSize = ''
switch (shoeSize) {
case 0 <= 7:
boardSize = '7.75'
break;
case 8,9:
boardSize = '8'
break;
case 10,11:
boardSize = '8.25'
break;
case 12,13:
boardSize = '8.38'
break;
case 14 >= 20:
boardSize = '8.5'
break;
default:
boardSize = '?'
document.write(boardSize)
}
<p>
Most people pick their board size by prefrence but I will make a tool below to choose a board size that will fit your shoe size best. The most popular board sizes are 7.75, 8, 8.25, 8.38, and 8.5. <br> <br>
If your shoe size is: <input id='shoeSize' type="text" class="shoe">. The best board size for you would be:
</p>
無論我在文本框中輸入什么,總會有一個“?” 這顯示在我的網站上。我能做什么/改變來解決這個問題。我想要發生的是,如果有人在文本框中鍵入例如“10”,則應列印“8.25”。我也很感激任何其他改進我的代碼的技巧。
uj5u.com熱心網友回復:
你有幾個問題:
document.getElementById('shoeSize').value 回傳一個字串,您應該使用 parseInt 函式將字串轉換為整數。然后處理在文本框中輸入文本的情況。parseInt 然后將回傳 NaN。(您也可以將輸入型別更改為數字以防止出現這種情況)。
我認為您的 javascript 在頁面加載時正在運行,而不是在輸入更改時,最簡單的方法是將 onchange 屬性添加到您的輸入中。
我對此不太確定,但 switch 陳述句看起來
14 >= 20也不正確,據我所知也不應該起作用。
這是正在運行的 jsfiddle 演示:https ://jsfiddle.net/cry9xzhb/13/
uj5u.com熱心網友回復:
嘗試這個:
const shoeSizeInput = document.getElementById('shoeSize')
const shoeSizeResult = document.getElementById('resultSize') // Get reference for the element where you want to display result
// Add event listener which will fire when input is changing
shoeSizeInput.addEventListener('input', (event) => {
const shoeSize = parseInt(event.target.value) // Get input value and parse to number
let boardSize = '?'
switch (true) {
case 0 <= shoeSize && shoeSize <= 7:
boardSize = '7.75'
break;
case shoeSize === 8 || shoeSize === 9:
boardSize = '8'
break;
case shoeSize === 10 || shoeSize === 11:
boardSize = '8.25'
break;
case shoeSize === 12 || shoeSize === 13:
boardSize = '8.38'
break;
case 14 <= shoeSize && shoeSize <= 20:
boardSize = '8.5'
break;
}
shoeSizeResult.textContent = boardSize // Set text of result element to board Size
})
<p>Most people pick their board size by prefrence but I will make a tool below to choose a board size that will fit your shoe size best. The most popular board sizes are 7.75, 8, 8.25, 8.38, and 8.5.</p>
<label>If your shoe size is:</label><input id='shoeSize' type="number" class="shoe">
<p id="resultSize"></p>
我改變了什么:
- 添加了一個事件監聽器。您在頁面加載時立即檢查了輸入值。因此它總是空的。
- 更改了 switch 陳述句。您可以在此處閱讀更多相關資訊:在 JavaScript 中打開整數范圍
- 添加了一個
p標簽來顯示結果。這比writeDocument().
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/375764.html
