單選按鈕點擊相關文字選中
情景:在一個HTML的頁面中設計一個表單,要求需要有單選框,並且通過點擊單選框后面的相關文字既可以得到選中。
主要兩種方法實現,方法1:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>FIRST PAGE</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <style> h2{text-align:center} </style> </head> <body> <form action=""> <h2>選擇</h2><hr> 您最喜歡水果?<br> <input type ="radio" name = "fruit" value ="" checked>蘋果<br> <label><input type ="radio" name = "fruit" value ="">桃子</label><br> <label><input type ="radio" name = "fruit" value ="">香蕉</label><br> <label><input type ="radio" name = "fruit" value ="">梨</label><br> <label><input type ="radio" name = "fruit" value ="">其他</label> </form> </body> </html>
在上述的代碼中
1.有“蘋果”的一項沒有標簽<label>所以必須通過點擊前面的單選按鈕選擇,后面的選項直接點擊相關的文字即可。
2.因為在input標簽中添加了“checked”,所以當頁面加載完之后“蘋果”選項是被選中的(即默認選中)。如果想要用JavaScript語句實現可以在改代碼后面添加如下的語句:
<script>document.getElementsByName("fruit")[0].checked="checked";</script>//默認的選中第一個選項
方法2:
<label for="apple">蘋果</label> <input type = "radio" id = "apple" name = "fruit"><br> <label for="peach">桃子</label> <input type = "radio" id = "peach" name = "fruit"><br> <label for="banana">香蕉</label> <input type = "radio" id = "banana" name = "fruit"><br> <label for="pear">梨</label> <input type = "radio" id = "pear" name = "fruit"><br> <label for="other">其他</label> <input type = "radio" id = "pear" name = "fruit"><br>
在方法1的基礎上實現。可見兩者之間的簡易程度不一。
參考:http://www.cnblogs.com/kingwell/archive/2012/09/28/2707132.html
http://www.divcss5.com/html/h490.shtml