根据在输入框中输入的值更改 HTML 文本

Changing HTML text based on a value entered into an input box

我正在创建一个网站,并想制作一个工具,使用 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”。我也很感激任何其他改进我的代码的技巧。

你有几个问题:

  1. document.getElementById('shoeSize').value return是一个字符串,你应该使用parseInt函数将字符串转换为整数。然后处理在文本框中输入文本时的情况。然后 parseInt 将 return NaN。 (您也可以将输入类型更改为数字以防止出现这种情况)。

  2. 你的 javascript 在页面加载时 运行 我认为,而不是在输入更改时最简单的方法是将 onchange 属性添加到你的输入中。

  3. 我不太确定,但是 switch 语句看起来也不对 14 >= 20 据我所知不应该工作。

这是有效的 jsfiddle 演示: https://jsfiddle.net/cry9xzhb/13/

试试这个:

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 语句。您可以在此处阅读更多相关信息:Switch on ranges of integers in JavaScript
  • 添加了一个 p 标签来显示结果。 这比 writeDocument() 好。