Почему мой прослушиватель событий onclick на моих переключателях не работает? - PullRequest
0 голосов
/ 06 мая 2020

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

Итак, я пытаюсь заставить плитку менять цвет при наведении курсора в зависимости от того, какой параметр выбран. (Для примера прямо сейчас он просто настроен на изменение цвета фона для простоты, хотя я до сих пор не понял, как это сделать на любом этапе). Итак, я попытался выполнить итерацию по группе форм, чтобы увидеть, проверено ли что-нибудь или нет, а затем, если он перейдет к вложенному l oop, который спрашивает, имеет ли значение определенный цвет. Мне кажется, что лог c у меня внизу, но ничего не активируется, и я не уверен, что еще я могу сделать. Но, очевидно, есть ошибка, которую я просто не улавливаю.

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

Ответы [ 2 ]

1 голос
/ 06 мая 2020

Вы также можете использовать селекторы CSS, чтобы захватить 'отмеченный' радиокнопку, выполнив document.querySelector('#color-options > input:checked'). Затем вы можете получить значение отмеченного переключателя, добавив .value в конец.

Итак, итого; document.querySelector('#color-options > input:checked').value. Цикл не требуется, параметры не требуются.

1 голос
/ 06 мая 2020

Вам не нужно вводить oop через форму, чтобы проверить, какой элемент отмечен. Достаточно использовать 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>
...