<html> <head> <script type="text/javascript" src="jquery-1.5.1.js"></script> <script type="text/javascript"> function choose(){ var choosed = $("input[name='choose']:checked").val(); if (choosed == 'div1') { $('#div1').show(); $('#div2').hide(); } else { $('#div1').hide(); $('#div2').show(); } } </script> </head> <body> <div> <input type='radio' value='div1' name='choose' checked='checked' onclick='choose()'/>div1 <input type='radio' value='div2' name='choose' onclick='choose()'/>div2 </div> <div id='div1' style='display:block'> this is div1 </div> <div id='div2' style='display:none'> this is div2 </div> </body> </html>
另外, .toggle()也可用于切换元素的可见状态。将可见元素置为隐藏,将隐藏置为可见的。
<html> <head> <script type="text/javascript" src="jquery-1.5.1.js"></script> <script type="text/javascript"> function choose(){ $('div').toggle() } </script> </head> <body> <input type='radio' value='div1' name='choose' checked='checked' onclick='choose()'/>div1 <input type='radio' value='div2' name='choose' onclick='choose()'/>div2 <div id='div1' style='display:block'> this is div1 </div> <div id='div2' style='display:none'> this is div2 </div> </body> </html>