【问题标题】:Radio button malfunctioning when used inside label tag在标签标签内使用时单选按钮出现故障
【发布时间】:2013-06-02 16:27:42
【问题描述】:

我正在研究 html 和 CSS。我必须在我的页面上添加 5 个单选按钮,并且我已在 <label> 标记中添加。但是当我寻找页面时。它显示所有选中的单选按钮,我也无法取消选择它。问题是我一次只需要选择一个单选按钮。这是我的代码。

<label class="radio"><input type="radio"> Pepse</label> 
<label class="radio"><input type="radio"> Coke</label> 
<label class="radio"><input type="radio">Mirinda</label>
<label class="radio"><input type="radio">Maaza </label>

【问题讨论】:

    标签: javascript html radio-button radiobuttonlist


    【解决方案1】:

    单选按钮需要一个通用名称。如果你不给他们name 属性,每个单选按钮本质上都会变成一个单向复选框。您可以选择它们,但不能取消选择它们。

    <input type="radio" name="foo" value="1" />
    <input type="radio" name="foo" value="2" />
    
    <input type="radio" value="3" />
    

    在这种情况下,两个 foo 单选按钮将在内部链接,因为它们的名称相同,但值为 3 的单选按钮将完全独立并按照您的方式行事。

    【讨论】:

    • Fantastic marc B. 有没有人说你是天才。它工作得很好。非常感谢您提供这个令人兴奋的事实。
    【解决方案2】:

    添加组名。

    jsFiddle

    <label class="radio"><input name="drinks" type="radio">Pepse</label>
    <label class="radio"><input name="drinks" type="radio">Coke</label>
    <label class="radio"><input name="drinks" type="radio">Mirinda</label>
    <label class="radio"><input name="drinks" type="radio">Maaza </label>
    <label class="radio"><input name="drinks" type="radio">Milk Frothers</label>
    

    【讨论】:

      【解决方案3】:

      1.一组无线电需要一个名称,以便浏览器知道选择了哪一个

      2.如果你想把标签放在输入之外你可以使用 for 属性 告诉浏览器这个标签是给那个具有相同 id

      的收音机的
      <label for="a">a</label>
      <input type="radio" name="aname" id="a" value="a"><br>
      <label for="b">b</label>
      <input type="radio" name="aname" id="b" value="b"><br>
      <label for="c">c</label>
      <input type="radio" name="aname" id="c" value="c"><br>
      <label for="d">d</label>
      <input type="radio" name="aname" id="d" value="d"><br>
      

      但我也更喜欢标签内的收音机

      <label><input type="radio" name="aname" value="a">a</label><br>
      <label><input type="radio" name="aname" value="b">b</label><br>
      <label><input type="radio" name="aname" value="c">c</label><br>
      <label><input type="radio" name="aname" value="d">d</label><br>
      <label><input type="radio" name="aname" value="e">e</label><br>
      

      3.通常他们也需要一个值,除了你使用js

      <label><input type="radio" name="aname">a</label><br>
      <script>
      document.write(document.getElementsByTagName('label')[0].childNodes[1].nodeValue)
      </script>
      

      &lt;br&gt;之后写一个

      【讨论】:

        猜你喜欢
        • 2016-05-21
        • 2012-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多