javascript - 如何根据用户选择的 HTML 选项更改选择的背景颜色?
问题描述
当用户选择红色选项然后选择全红色的背景时,我想更改选择的背景颜色。当用户选择粉红色时,选择背景颜色为粉红色。尝试解决这个问题大约 3 个小时。
我已经尝试了 addEventListener,也在选择中进行了 onchange,但没有工作。
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 = red、pink、yellow。选择的颜色只改变一次红色,如果你选择另一个选项 - 什么也不会发生。编辑器或控制台中没有错误。希望有人可以帮助我,非常感谢。
解决方案
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>
推荐阅读
- c++-winrt - Storyboard_Completed 事件产生链接器工具错误 LNK2019 错误
- css - 如何直接扩展 SCSS 父选择器?
- android - 我正在使用从活动到布局的 Android 数据绑定作为字符串,但它没有显示
- angular - HTTP 拦截器两次发送相同的请求
- c - 处理 QEMU 设备中配置空间的 PCI 读/写
- r - 如何根据分类变量将图例分成多个组
- javascript - 使用节点如何将我的 ES6-export-default 模块导入我的命令行 javascript 程序?
- c++ - Windows 10 中的 boost::filesystem::remove_all 有问题
- sql - SQL 确定具有相同成员的团队
- python-3.x - 如何正确访问 3D-Pytorch-Tensor 中的元素?