首页 > 解决方案 > 将 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 类型更改为许多不同的东西。我只是不明白。

标签: javascriptinlineexternal

解决方案


您需要为更改事件附加处理程序

document.getElementById("colors").addEventListener('change', function (){ //Your logic goes here });


推荐阅读