为什么我的单选按钮上的 onclick 事件侦听器不起作用?



<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';
}
}
} 
} 
}

因此,我试图让瓷砖在悬停时根据选择的选项更改颜色。(对于现在的例子,为了简单起见,它只是设置为更改背景颜色,尽管我还没有想好在悬停时这样做(。因此,我试图对表单组进行迭代,看看是否有任何内容被选中,然后如果是,则转到一个嵌套循环,询问值是否为特定颜色。我觉得我的逻辑是正确的,但什么都没有激活,我不确定我还能做什么。但很明显,我只是没有抓住一个错误。

https://jsfiddle.net/Jbautista1056/0gxf2Lpq/1/

您不需要遍历表单来检查检查了哪个元素。使用updateColor(this)就足够了:

function updateColor(element) {
const selectedColor = element.value !== 'user' ? element.value : 'green';
const title = document.getElementById("tile");
tile.style.backgroundColor = selectedColor;
}
#tile {
width: 100px;
height: 100px;
border: 1px solid #000;
}
<input type="radio" name="choice" value="blue" onclick="updateColor(this)">
<label for="blue">Blue</label>
<input type="radio" name="choice" value="red" onclick="updateColor(this)" >
<label for="red">Red</label>
<input type="radio" name="choice" value="white" onclick="updateColor(this)" >
<label for="white">White</label>
<input type="radio" name="choice" value="user" onclick="updateColor(this)">
<label for="white">User</label>
<br /><br />
<div id="tile"></div>

您还可以使用CSS选择器通过执行document.querySelector('#color-options > input:checked')来获取"checked"单选按钮。然后,您可以通过在末尾添加.value来获得选中单选按钮的值。

所以总的来说;document.querySelector('#color-options > input:checked').value。不需要循环,不需要参数。

最新更新