使用 JavaScript 和无线电输入更改 HTML 中的背景颜色有什么错误

What is the Error in changing Background Color in HTML using JavaScript and radio input

本文关键字:背景 颜色 错误 什么 HTML JavaScript 无线电 输入 使用      更新时间:2023-10-14
<!-- What is the error ? -->
<!doctype html>
<html>
<head>
    <title>JS 5</title>
    <script type="text/javascript">
        //javascript function to change color according to input
        function changeCol(){
            var x=document.getElementById("col").value;
            if(x=="red"){
                document.bgColor="red";
            }
            else if(x=="green"){
                document.bgColor="green";
            }
            else{   
                document.bgColor=yellow";
            }
        }
    </script>
</head>
<body>
    <h1> BODY </h1> 
    <form>
        <fieldset>
            <legend>Choose One</legend>
            <input type="radio" id="col" value="red">Red<br>
            <input type="radio" id="col" value="green">Green<br>
            <button id="x" onClick="changeCol()">Change</button>
        </fieldset>
    </form>
</body>
</html>

无法收到错误。似乎一切都很好:(功能更改Col应根据无线电输入的选择更改颜色。但它什么也没做。

您没有 2 个具有相同 ID 的元素。

function changeCol(){
            var x1=document.getElementById("col1");
            var x2=document.getElementById("col2");
            if(x1.checked){
                document.bgColor="red";
            }
            else if(x2.checked){
                document.bgColor="green";
            }
            else{   
                document.bgColor=yellow";
            }
        }

<input type="radio" id="col1" value="red">Red<br>
<input type="radio" id="col2" value="green">Green<br>

这里有一个语法错误,所以 Javascript 代码根本无法启动:

 document.bgColor=yellow";

它应该是:

 document.bgColor="yellow";

运行它后,您将看到无论您选择什么,它只会将颜色更改为红色。该 id 在页面中应该是唯一的。当您有重复项时,getElementById只会为您提供第一个元素。

不过,如果您只查看value属性,获取多个元素对您没有帮助。无论是否选择单选按钮,这都不会更改。应使用 checked 属性来检测这一点。

首先给单选按钮不同的id:

<input type="radio" id="red" value="red">Red<br>
<input type="radio" id="green" value="green">Green<br>

现在,您可以检查每个单选按钮的状态:

function changeCol() {
  var red = document.getElementById("red");
  var green = document.getElementById("green");
  if (red.checked) {
    document.bgColor = "red";
  } else if (green.checked) {
    document.bgColor = "green";
  } else {   
    document.bgColor = "yellow";
  }
}