在我的表格中,我有一个选择字段;
<select id="setColor">
<option value="black">black</option>
<option value="white">white</option>
<option value="both">both</option>
</select>
每当选择每个选项时,我都希望发生不同的事情;
<script>
var setColor = function(){
var selectVal = $("#setColor").val();
if(selectVal === "black"){
//do something when "black" is selected
}
else if(selectVal === "white"){
//do something when "white" is selected
}
else {
//do something when "both" is selected
}
};
$(document).ready(setColor());
</script>
这已在Execute script based on which option is selected in a select box?中得到解答,但问题是,每当添加更多选项(例如颜色)时,我将不得不在JS中添加更多代码。所以问题是,是否有更好的方法来编写JS / Jquery以防止我在添加选项时添加更多代码。