2014-10-10 136 views
0

我试图编码它,就好像当我解开复选框时,下拉菜单的两个选项都应该变为只读,但是当前只有第二个下拉菜单变为只读,第一个不会变成只读只读并保持可编辑,这里有什么问题?为什么只有在取消选中复选框后,第一个下拉菜单才会变为只读状态?JavaScript代码不起作用

<html> 
 
    <head> 
 
    <script type="text/javascript"> 
 
    function myFunction() { 
 
     document.getElementById("1").disabled = false; 
 
    } 
 
    
 
    function mySecondFunction() { 
 
    var ddl = document.getElementById("1"); 
 
    var selectedValue = ddl.options[ddl.selectedIndex].value; 
 
     if (selectedValue == "ExceptionZero") 
 
     { 
 
     document.getElementById("mySelection").disabled = true; 
 
    \t //set default 
 
    \t document.getElementById("mySelection").value = "OptionZero" 
 
     }else { 
 
     document.getElementById("mySelection").disabled = false; 
 
     } 
 
     
 
    } 
 
    
 
    function myThirdFunction(){ 
 
    \t document.getElementById("mySelection").disabled = true; 
 
    \t //set default 
 
    \t document.getElementById("mySelection").value = "OptionZero" 
 
    \t 
 
    \t //first drop down 
 
    \t document.getElementById("1").disabled = true; 
 
    \t document.getElementById("1").value = "OptionZero" 
 
    } 
 
    
 
    </script> 
 
    
 
    </head> 
 
    <body> 
 
    <input type="checkbox" name="selectionbox" value="Yes" onclick="myFunction()" onchange="myThirdFunction()"/> 
 
    
 
    <select disabled id="1" onchange="mySecondFunction()"> 
 
    \t \t \t \t <option value="OptionZero">Default</option> 
 
    \t \t \t \t <option value="OptionOne">Car</option> 
 
    \t \t \t \t <option value="OptionTwo">Car2</option> 
 
    \t \t \t \t <option value="OptionThree">Car23</option> 
 
    </select> 
 
    <br> 
 
    \t <select disabled id="mySelection"> 
 
    \t \t \t \t <option value="OptionZero">Default</option> 
 
    \t \t \t \t <option value="OptionOne">A</option> 
 
    \t \t \t \t <option value="OptionTwo">B</option> 
 
    \t \t \t \t <option value="OptionThree">C</option> 
 
    \t </select> 
 
    </body> 
 
    </html>

+0

你为什么使用onclick和onchange两个函数。你不能用吗? – TBI 2014-10-10 14:02:57

+0

由于myFunction被称为onclick,并且这发生在onchange事件之后,因此每次单击复选框时总是将disabled设置为false。 – Namrehs 2014-10-10 14:04:02

+0

我不确定,如果事件的触发顺序(点击和更改)在不同的浏览器中是相同的。无论如何,您应该只使用一个事件来检测更改,通常是在复选框上单击'click',因为'change'不会在所有浏览器中立即触发。 – Teemu 2014-10-10 14:07:07

回答

0

你的onClick事件onChange事件后再次被调用,导致箱1,以启用。尝试改变你的onclick这个并删除你的thirdFunction事件。

JSFiddle

function myFunction() { 
     if (document.getElementById("1").disabled == false) { 
      document.getElementById("mySelection").disabled = true; 
      //set default 
      document.getElementById("mySelection").value = "OptionZero" 

      //first drop down 
      document.getElementById("1").disabled = true; 
      document.getElementById("1").value = "OptionZero"  
     } else { 
      document.getElementById("1").disabled = false; 
     } 
    } 

事件调用的顺序可以通过浏览器有所不同,所以你应该只有一个事件时,为了使对输出的差异。