新手 – 我想用这些复选框做两件事:
>使用TAB键选项卡,这部分有效
>当我选择TAB时,我想按ENTER键选择该复选框,这部分不起作用
以下是示例代码.我使用复选框作为一个组.
有没有人有什么建议?
<!doctype html> <head> <title>test Radio buttons checkBox</title> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('input:checkBox[name=Colors]').keypress(function(event) { var keycode = (event.keyCode ? event.keyCode : event.which); if (keycode == 13) { CheckBox_to_RadioButton(this); alert("Enter key was pressed"); } event.stopPropagation(); }); $('input:checkBox[name=Colors]').click(function(){ CheckBox_to_RadioButton(this); }); }); function CheckBox_to_RadioButton(Box){ $('input:checkBox[name=' + Box.name + ']').each(function(){ if (this != Box) $(this).attr('checked',false); }); } </script> </head> <body> <h1>test Radio buttons checkBox</h1> <form name="form1"> <input type="text" id="dname" name="dname"><br> <input type="checkBox" id="Colors" name="Colors" value="Red" />Red<br /> <input type="checkBox" id="Colors" name="Colors" value="Blue" />Blue<br /> <input type="checkBox" id="Colors" name="Colors" value="Green" />Green<br /> <input type="checkBox" id="Colors" name="Colors" value="Yellow" />Yellow<br /> <br> </form> </body> </html>
解决方法
试试这个代码
<!doctype html> <html> <head> <title>test Radio buttons checkBox</title> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('input:checkBox[name=Colors]').keypress(function(event) { var keycode = (event.keyCode ? event.keyCode : event.which); if (keycode == 13) { CheckBox_to_RadioButton(this,"enter"); } event.stopPropagation(); }); $('input:checkBox[name=Colors]').click(function(){ CheckBox_to_RadioButton(this,"click"); }); }); function CheckBox_to_RadioButton(Box,myEvent){ if(myEvent == "enter") { var $Box = $(Box); if($Box.attr('checked')) $Box.attr('checked',false); else $Box.attr('checked',true); } $('input:checkBox[name=' + Box.name + ']').each(function(){ if (this != Box) $(this).attr('checked',false); }); } </script> </head> <body> <h1>test Radio buttons checkBox</h1> <form name="form1"> <input type="text" id="dname" name="dname"><br> <input type="checkBox" id="Colors" name="Colors" value="Red" />Red<br /> <input type="checkBox" id="Colors" name="Colors" value="Blue" />Blue<br /> <input type="checkBox" id="Colors" name="Colors" value="Green" />Green<br /> <input type="checkBox" id="Colors" name="Colors" value="Yellow" />Yellow<br /> <br> </form> </body> </html>