javascript - 将 onchange 脚本内联到外部 JS
问题描述
我有一个表单选择器元素,它在 onchange 之后有一个内联脚本:
<select onchange="this.className=this.options[this.selectedIndex].className">
<option value="select">Select color</option>
<option class="greenOpt" value="green" >Green</option>
<option class="yellowOpt" value="yellow" >Yellow</option>
<option class="blueOpt" value="blue" >Blue</option>
</select>
这非常适合我的输出,将选项的背景颜色更改为与其单词相同的颜色,绿色是绿色,黄色是黄色等。
.greenOpt{
background-color: green;
text-shadow: -1px 0 white, 0 1px white, 1px 0 white, 0 -1px white;
}
.blueOpt{
background-color: blue;
text-shadow: -1px 0 white, 0 1px white, 1px 0 white, 0 -1px white;
}
.yellowOpt{
background-color: yellow;
text-shadow: -1px 0 white, 0 1px white, 1px 0 white, 0 -1px white;
}
但我想将该onchange
脚本移动到外部函数中,但我不确定它应该是什么样子。我明白我需要在<select>
标签中做的是onchange="colorSel()"
到目前为止我的功能:
function colorSel() {
var colors = document.getElementById("colors");
colors = this.className = this.options[this.selectedIndex].className;
}
我难住了。我已经将函数的参数和 getElement 类型更改为许多不同的东西。我只是不明白。
解决方案
您需要为更改事件附加处理程序
document.getElementById("colors").addEventListener('change', function (){
//Your logic goes here
});
推荐阅读
- android - 如何将可变列表从片段传递到另一个片段?
- java - 如果我的条件没有得到尊重,如何停止阅读 NFC?
- html-table - 在 reStructuredText 的 Sphinx 处理中保留表格单元格换行符
- image-capture - Ecapture 模块未安装在 Python 3.9.1 中
- excel - VBA 与不同工作簿中的相同命名范围混淆
- r - 由于特定的正则表达式,如何使用 mutate(across()) 更改列?
- android - 有时,BottomSheetDialogFragment 在屏幕中心打开,如警报对话框
- esp32 - esp smartconfig 发生了什么,在 v4.1 中是一团糟?
- python - 如何在 Python 中创建一个有效的函数来填充因子 (t+1)
- bash - 即使在 If 块中,Makefile 也会引发错误