HTML嵌套单选按钮

时间:2010-01-14 01:11:57

标签: html

我有4个单选按钮(A,B,C,D)。当我点击单选按钮A时,会有另外两个选项 - A1和A2。其他人也会这样。如果我选择D2,则会出现另外2个单选按钮。

如何在HTML中执行此操作?

4 个答案:

答案 0 :(得分:6)

HTML和仅限CSS3版本(Fiddle):

组“D”的HTML(其他组类似)

<div>
    <input type="radio" name="level0" value="D" id="D"/>
    <label for="D">D</label>
    <div class="sub1">
        <div>
            <input type="radio" name="level1" value="D0" id="D0"/>
            <label for="D0">D0</label>
        </div>
        <div>
            <input type="radio" name="level1" value="D1" id="D1"/>
            <label for="D1">D1</label>
            <div class="sub2">
                <div>
                    <input type="radio" name="level2" value="D10" id="D10"/>
                    <label for="D10">D1-0</label>
                </div>
                <div>
                    <input type="radio" name="level2" value="D11" id="D11"/>
                    <label for="D11">D1-1</label>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

.sub1, .sub2 { display: none; }

:checked ~ .sub1, :checked ~ .sub2 {
    display: block;
    margin-left: 40px;
}

答案 1 :(得分:1)

您只能在文档中的一个元素上使用特定ID。你必须在每个元素上加上不同的id,并使它们分开显示:

<input onclick="document.getElementById('extra1').style.visibility='visible';document.getElementById('extra2').style.visibility='visible';" type="radio" />Apple

<input type="radio" id="extra1" style="visibility:hidden" other choice here />

<input type="radio" id="extra2" style="visibility:hidden" other choice here />

答案 2 :(得分:1)

如果你想在选择某个单选按钮时出现更多单选按钮,我建议不要在html中将它们“嵌套”在一起。当javascript被选中时,让javascript显示隐藏的组或RB。

坦率地说,我认为使用单选按钮显示一个选择框会更加用户友好,因为很明显你是从另一个组中选择的。太多的单选按钮总是看起来很难看。

代码的其他问题:id应该是唯一的,将RB文本放在单选按钮旁边而不是标记内,并尽可能避免基于表格的布局。内联javascript和css也应该避免,但因为这是一个代码示例,它实际上使它更具可读性。哦,最重要的是,你有其他按钮设置为onclick,所以如果你取消选择RB它们就不会消失:D

答案 3 :(得分:0)

@guffa我想我会稍微修改你的答案。将所有可选单选按钮放在<div>元素中,如下所示:

<input onclick='document.getElmentById("optional_buttons").style.display="block"' type="radio" />
<div id="optional_buttons" style="display: none;" >
optional radio buttons
</div>