简体   繁体   English

Javascript Select OnChange第二次无效

[英]Javascript Select OnChange doesn't work second time

I would like to create an html table with some td cells that could change background color,from red to green ("C" to "A") and from green to red ("A" to "C"), using "select onchange". 我想创建一个带有一些td单元格的html表,该单元格可以使用“ select onchange”将背景颜色从红色更改为绿色(“ C”更改为“ A”),从绿色更改为红色(“ A”更改为“ C”) ”。 It works the first time, but not the second. 它是第一次工作,但是第二次却没有。

Here is the JS 这是JS

<script type="text/javascript">
function change(id){
var x=document.getElementById(id);
x.style.backgroundColor="#e50017";//red
}
function exchange (id){
var x=document.getElementById(id);
x.style.backgroundColor="#009900";//green
}
</script>

Here is the HTML 这是HTML

<form id="menuForm" name="menuForm" >
<table summary="layout table">
<tbody>
<tr>
           <td rowspan="1" colspan="1" id="prova" width="35px" align="center" bgcolor="#e50017">
            M
            <br>
            <select onchange="exchange('prova')" name="select1">
            <option value="0" selected="selected">C</option>
            <option value="1">A</option>
            </select>
            </td>
            <td rowspan="1" colspan="1" id="prova1" width="35px" align="center" bgcolor="#009900">
            M
            <br>
            <select onchange="change('prova1')" name="select2">
            <option value="1" selected="selected">A</option>
            <option value="0">C</option>
            </select>
            </td>
        </tr>
      </tbody>
    </table>     
</form>

I would recommend to toggle class names instead. 我建议改为切换类名。 It will make it much simple and flexible - for example it's easy to change not only background color but any other styles without even touching javascript function: 这将使它变得更加简单和灵活-例如,即使不更改javascript函数,也可以轻松更改背景颜色和其他任何样式:

 function change(id) { var x = document.getElementById(id); x.className = x.className === 'red' ? 'green' : 'red'; } 
 .red { background: #e50017; } .green { background: #009900; } 
 <form id="menuForm" name="menuForm"> <table summary="layout table"> <tbody> <tr> <td rowspan="1" colspan="1" id="prova" width="35px" class="red" align="center">M <br> <select onchange="change('prova')" name="select1"> <option value="0" selected="selected">C</option> <option value="1">A</option> </select> </td> <td rowspan="1" colspan="1" id="prova1" width="35px" class="green" align="center">M <br> <select onchange="change('prova1')" name="select2"> <option value="1" selected="selected">A</option> <option value="0">C</option> </select> </td> </tr> </tbody> </table> </form> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM