我正在尝试更改元素的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()">
答案 0 :(得分:1)
您将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()">
答案 1 :(得分:1)
在持有单选按钮的情况下,您没有使用变量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");
}
}
&#13;
<input type="radio" name="lala" value="human" onclick="ways()">
<input type="radio" name="lala" value="robot" onclick="ways()">
&#13;
答案 2 :(得分:0)
js引擎找不到变量lala
。可能你在控制台中得到Uncaught ReferenceError: lala is not defined
。
使用以下代码
function ways() {
if(document.getElementsByName("lala")[0].checked) {
alert("this is so cool it's finally working");
}
else if(document.getElementsByName("lala")[1].checked) {
alert("Alhamdulillah it's all going great");
}
}