如何根据用户选择的HTML选项更改select的背景颜色?

时间:2019-07-12 19:15:29

标签: javascript html select

当用户选择红色选项,然后选择全红色背景时,我想更改选择的背景色。当用户选择粉红色时,则选择背景色为粉红色。尝试解决此问题大约3个小时。

我已经尝试过addEventListener,但在select中也发生了变化,但不起作用。

const select = document.querySelector('#select');

select.addEventListener('change', (event) => {
  console.log(event.target.value)

  if (event.target.value = 'red') {
    select.style.background = 'red';
  }
  else if (event.target.value = 'pink') {
    select.style.background = 'pink'
  }
  else {
    select.style.background = 'yellow'
  }
});
<select id="select">
  <option value="red">red</option>
  <option value="pink">pink</option>
  <option value="yellow">yellow</option>
</select>

在控制台中,我可以看到event.target.value =红色,粉红色,黄色。选择的颜色仅更改一次红色,如果您选择其他选项,则什么也不会发生。编辑器或控制台中没有错误。希望有人能帮助我,非常感谢。

3 个答案:

答案 0 :(得分:1)

document.querySelector是一种方法,因此应将其作为函数调用:

document.querySelector('#select')

此外,您可以直接将选择值写为背景色,这样就不需要if / else条件:

select.style.background = event.target.value

最终版本可能如下所示:

const select = document.querySelector('#select');

select.addEventListener('change', (event) => {
 select.style.background = event.target.value
});
<select id="select"> 
  <option value="red">red</option>
  <option value="pink">pink</option>
  <option value="yellow">yellow</option>
</select>

答案 1 :(得分:0)

首先,您错误地定义了select。其次,您的if谓词应使用相等比较器===,而不是赋值运算符=

const select = document.querySelector('#select');

select.addEventListener('change', (event) => {
  console.log(event.target.value)

  if (event.target.value === 'red') {
    select.style.background = 'red';
  } else if (event.target.value === 'pink') {
    select.style.background = 'pink'
  } else {
    select.style.background = 'yellow'
  }
});
<select id="select">
  <option value="red">red</option>
  <option value="pink">pink</option>
  <option value="yellow">yellow</option>
</select>

答案 2 :(得分:0)

您使用的querySelector错误。应该以选择器作为参数的方法来调用它,就像这样:

const select = document.querySelector('#select');

相关问题