This question already has answers here:
Using radio button to trigger an action
                                
                                    (2个答案)
                                
                        
                                去年关闭。
            
                    
我试图更改元素的innerHTML,或者甚至只是在用户单击广播时警告某些内容。

这是我的JavaScript:

function ways() {
    var set = document.getElementsByName("lala");

    if(lala[0].checked) {
        alert("this is so cool it's finally working");
    }
    else if(lala[1].checked) {
        alert("Alhamdulillah it's all going great");
    }
}


这是我的HTML:

<input type="radio" name="lala" value="human" onclick="ways()">
<input type="radio" name="lala" value="robot" onclick="ways()">

最佳答案

document.getElementsByName("lala")的结果放置在名为set的变量中。您从未定义过名为lala的变量,因此,要访问这些元素,必须访问set

关于您的代码的所有其他信息都是正确的。



function ways() {

  var set = document.getElementsByName("lala");

  if (set[0].checked) {
    alert("this is so cool it's finally working");
  } else if (set[1].checked) {
    alert("Alhamdulillah it's all going great");
  }
}

<input type="radio" name="lala" value="human" onclick="ways()">
<input type="radio" name="lala" value="robot" onclick="ways()">

09-19 08:57