使用 JavaScript 和无线电输入更改 HTML 中的背景颜色有什么错误
What is the Error in changing Background Color in HTML using JavaScript and radio input
<!-- 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";
}
}
相关文章:
- 使用JS如何动态更改显示的html文件中的文本背景颜色
- 如何使用jquery更改html中的背景颜色
- Javascript对象类在单击时打开窗口进行颜色选择,并在更改时替换对象背景颜色
- JS幻灯片与CSS背景颜色变化
- DT数据表背景颜色为黑色,但仍有悬停和选择颜色
- Javascript通过列表项的函数和css来更改背景颜色
- Javascript没有从数组中选择背景颜色
- 使用圆中的数组更改背景颜色项目
- 如何用jquery动画改变背景颜色,就像一个过渡
- 使用jquery交换并保存背景颜色
- j查询如何设置/取消设置下拉菜单的背景颜色
- 使用angularjs根据时间更改背景颜色
- 设置Dojo量表的背景颜色
- javascript样式的背景颜色在设置时闪烁.ASP.NET
- 使用javascript更改任意文本的背景颜色
- 在用Javascript更改背景颜色后:hover don'不要改变颜色
- 图像内部的透明背景颜色不受影响
- jQuery mobile-动态更改ui页面背景颜色
- 切换按钮的背景颜色
- JavaScript更改类的背景颜色