如何根据单选按钮选择以特定的跨度样式显示文本?

时间:2019-11-24 10:12:45

标签: javascript

<html>
    <head>
        <script>
          function check(){
          var button =document.getElementsByName("rdName");
          //rdName is the name of the radio buttons//
          var style =document.getElementsByName("spans");
          // spans is the name of the span tags included//
          for(var i=0; i<button.length;i++){
             if(button[i].checked == true){
                 document.getElementById(style[i].id).innerHTML ="YOU ARE:" + button[i].value;
             }
          }
        }
        </script>
    </head>
    <body>
    <form id="myForm">
        <center>
            <input type="radio" id="radio1" name="rdName" onclick="check()" value="male"> male
            <input type="radio" id="radio2" name="rdName" onclick="check()" value="female">female
            // corresponding span tags for the radio buttons//
            <span id="sp1" name="spans" style="background:red"></span>
            <span id="sp2" name="spans" style="background:blue"></span>
         </center>
    </form>
    </body>
    </html>

这里我有2个按钮和2个span标签。 当单击第一个按钮时,我想以第一个跨度样式显示文本。 当选择第二个按钮时,我需要以第二个跨度样式显示文本。 这段代码有效,但是当我单击第一个单选按钮后单击“选择第二个单选按钮”时,在窗口中出现两个跨度不同的文本。 我只想查看一次选中的单选按钮的特定跨度样式。

3 个答案:

答案 0 :(得分:1)

添加else条件将帮助您显示单击单选按钮所对应的范围。这是更新的代码。希望对您有帮助!

if(button[i].checked == true){
                 document.getElementById(style[i].id).innerHTML ="YOU ARE:" + button[i].value;
             }
// add this to your code.
else{
     document.getElementById(style[i].id).innerHTML ="";
}

说明

如果对男性的检查为真,则显示YOU ARE:MALE,对于第二个跨度,将其设置为空字符串。如果是女性,反之亦然。

答案 1 :(得分:1)

您不需要JavaScript,因为可以在纯CSS中完成。在CSS中,您可以使用:chekced选择处于选中状态的输入。您可以在初始加载时隐藏#sp1, #sp2,然后根据检查的值显示。在CSS中使用~会选择任何同级(相邻或不相邻)。

#sp1,
#sp2 {
  display: none;
}

input[value="male"]:checked~#sp1 {
  display: initial;
}

input[value="female"]:checked~#sp2 {
  display: initial;
}
<form id="myForm">
  <center>
    <input type="radio" id="radio1" name="rdName" value="male"> male
    <input type="radio" id="radio2" name="rdName" value="female">female // corresponding span tags for the radio buttons//
    <span id="sp1" name="spans" style="background:red">YOU ARE: male</span>
    <span id="sp2" name="spans" style="background:blue">YOU ARE: female</span>
  </center>
</form>

答案 2 :(得分:0)

Adding 2 lines inside for worked:


for(var i=0; i<button.length;i++){
                 document.getElementById(style[i].id).style.display = "none";
                 if(button[i].checked == true){
                     document.getElementById(style[i].id).style.display = "block";
                     document.getElementById(style[i].id).innerHTML ="YOU ARE:" + button[i].value;
                 }
              }