首页 > 解决方案 > 尝试查找对输入表单的响应时,getElementById 始终返回 null

问题描述

我正在尝试学习 JavaScript,并且我现在已经多次使用 getelementbyid 重用此输入代码,但突然它决定中断并且不会返回除 null 之外的任何内容,我不知道如何修复它。

function FindRadioButton() {
  const rbs = document.querySelectorAll('input[name="choice"]');
  let selectedValue;
  for (const rb of rbs) {
    if (rb.checked) {
      selectedValue = rb.value;
      break;
    }
  }
  return selectedValue
}

function andorxor(num1, num2) {
  num1 = parseInt(document.getElementById("num1").value)
  num2 = parseInt(document.getElementById("num2").value)
  operator = FindRadioButton()
  if (operator == "AND") {
    document.getElementById("replaceable").innerHTML = num1 & num2

  } else if (operator == "OR") {
    document.getElementById("replaceable").innerHTML = num1 | num2

  } else if (operator == "XOR") {
    document.getElementById("replaceable").innerHTML = num1 ^ num2

  }
}
<h1>AND OR XOR BITWISE OPERATIONS</h1>

<form id="numbers">
  <input type="radio" id="AND" name="ANDORXOR" value="AND">AND <br>
  <input type="radio" id="OR" name="ANDORXOR" value="OR">OR <br>
  <input type="radio" id="XOR" name="ANDORXOR" value="XOR">XOR <br> First number: <input type="text" id="num1"><br> Second number: <input type="text" id="num2"><br><br>
  <input id="btn" type="button" onclick="andorxor(0, 0)" value="Calculate">
</form>

<p id="replaceable">Click "Calculate"</p>

标签: javascripthtmlgetelementbyid

解决方案


getElementById很好,您在FindRadioButton函数中使用了错误的名称:

const rbs = document.querySelectorAll('input[name="choice"]');

name="choice"应该与您的输入名称匹配name="ANDORXOR"::

<h1>AND OR XOR BITWISE OPERATIONS</h1>

<form id="numbers">
  <input type="radio" id="AND" name="ANDORXOR" value="AND">AND <br>
  <input type="radio" id="OR" name="ANDORXOR" value="OR">OR <br>
  <input type="radio" id="XOR" name="ANDORXOR" value="XOR">XOR <br> First number: <input type="text" id="num1"><br> Second number: <input type="text" id="num2"><br><br>
  <input id="btn" type="button" onclick="andorxor(0, 0)" value="Calculate">
</form>

<p id="replaceable">Click "Calculate"</p>

<script>
  function FindRadioButton() {
    const rbs = document.querySelectorAll('input[name="ANDORXOR"]');
    let selectedValue;
    for (const rb of rbs) {
      if (rb.checked) {
        selectedValue = rb.value;
        break;
      }
    }
    return selectedValue
  }

  function andorxor(num1, num2) {
    num1 = parseInt(document.getElementById("num1").value)
    num2 = parseInt(document.getElementById("num2").value)
    operator = FindRadioButton()
    if (operator == "AND") {
      document.getElementById("replaceable").innerHTML = num1 & num2

    } else if (operator == "OR") {
      document.getElementById("replaceable").innerHTML = num1 | num2

    } else if (operator == "XOR") {
      document.getElementById("replaceable").innerHTML = num1 ^ num2

    }
  }
</script>
javascript html typeerror


推荐阅读