"Javascript"中的单选按钮设置

M_B*_*216 2 html javascript jquery image

我有一组三个单选按钮连接一组三个图像 - 即{image1,radioBtn1},{image2,radioBtn2},{image3,radioBtn3}.

我正在尝试执行以下操作:当我单击一个图像时,连接到此按钮的单选按钮会自动变为"已选中"(例如:当我单击图像3时,将检查radioBtn3)

我试过以下代码:

HTML:

<input type="radio" id="radioBtb1" name="subject"/><a href="#"><img id="image1" src="../image/img3.png" height="150px"/></a>
<input type="radio" id="radioBtb2" name="subject"/><a href="#"><img id="image2" src="../image/img3.png" height="150px"/></a>
<input type="radio" id="radioBtb3" name="subject"/><a href="#"><img id="image3" src="../image/img3.png" height="150px"/></a>
Run Code Online (Sandbox Code Playgroud)

使用Javascript:

function selectSubject(){
    if(document.getElementById('image1'))
        document.getElementById(radioBtb1).checked=true;
    if(document.getElementById('personal'))
        document.getElementById(radioBtb2).checked=true;
    if(document.getElementById('image3'))
        document.getElementById(radioBtb3).checked=true;
}
Run Code Online (Sandbox Code Playgroud)

但那根本不起作用.

Joe*_*e50 6

您可以使用<label>标签轻松完成此操作.只需使用以下语法:

<label>
    <input type="radio" id="radioBtb1" name="subject"/>
    <img id="image1" src="../image/img3.png" height="150px"/>
</label>
<label>
    <input type="radio" id="radioBtb2" name="subject"/>
    <img id="image2" src="../image/img3.png" height="150px"/>
</label>
<label>
    <input type="radio" id="radioBtb3" name="subject"/>
    <img id="image3" src="../image/img3.png" height="150px"/>
</label>
Run Code Online (Sandbox Code Playgroud)

这将自动完成您正在寻找的.

  • 值得一提的是,您还可以将`<label>`与`<input>`相关联,而不使用`for`属性将它们包装在一起.例如,在这种情况下,`<label for ="radioBtb1">`,因为`radioBtb1`是`input`的`id`. (4认同)