单选按钮中实现点击文字选中

单选按钮点击相关文字选中

情景:在一个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

 

posted @ 2016-09-27 14:03  悟知清风  阅读(14415)  评论(0编辑  收藏  举报