【发布时间】:2020-08-21 16:13:03
【问题描述】:
<form id="color-options" name="FormB">
<input type="radio" name="choice" value="blue" onclick="updateColor()">
<label for="blue">Blue</label>
<input type="radio" name="choice" value="red" onclick="updateColor()" >
<label for="red">Red</label>
<input type="radio" name="choice" value="white" onclick="updateColor()" >
<label for="white">White</label>
<input type="radio" name="choice" value="user" onclick="updateColor()">
<label for="color-picker">Color Picker</label>
<input type="color" id="color-picker">
</form>
<div id="Sketch">
<div id="tile">
</div>
</div>
let tile = document.getElementById("tile")
let radio = document.forms[1] // //forms[1] is accessing the 2nd form because u have a form before it.
function updateColor() {
for (let i = 0; i < radio.choice.length; i++) { //document.forms returns a collection of everything that has a form tag
if (radio.choice[i].checked ) { //form.choice = returns an array of the radio buttons, incrementing i to traverse along the array
//checked returns a boolean if the button is checked or not; ask if the button is clicked or not and if it is follow this new loop
for (let i = 0; i < radio.choice[i].length; i++) { //this new loop iterates and asks if the value is a certain color, and if it is change the background color
if (radio.choice[i].value === "blue") {
tile.style.backgroundColor= "blue";
} else if (radio.choice[i].value === "red") {
tile.style.backgroundColor = 'red';
} else if (radio.choice[i].value === "white") {
tile.style.backgroundColor = 'white';
} else if (radio.choice[i].value === "user") {
tile.style.backgroundColor = 'green';
}
}
}
}
}
所以我试图让磁贴在悬停时根据选择的选项改变颜色。 (对于现在的示例,为了简单起见,它只是设置为更改背景颜色,尽管我还没有想出在悬停时这样做)。所以我试图做的是遍历表单组以查看是否检查了任何内容,然后是否移动到嵌套循环,询问该值是否为某种颜色。我觉得我的逻辑是正确的,但没有任何反应,我不确定我还能做什么。但显然有一个错误我只是没有抓住。
【问题讨论】:
标签: javascript html dom radio-button dom-events