为什么我的按钮onclick功能不能正常工作
Why my button onclick function not working properly ?
最后的按钮"fight"没有按预期工作。我计划有更多的变量和战斗按钮将与赢家警报。目前,如果一个是水,另一个是火;水赢了。
但是目前它总是提醒else, "rofl so noob neither wins"。
HTML:Pokem8's Element:
<input type="radio" name="element" value="1"> Water
<input type="radio" name="element" value="2"> Fire
Other guy's Element:
<input type="radio" name="other" value="1"> Water
<input type="radio" name="other" value="2"> Fire
<button id="fight">FIGHT</button>
Javascript: var ele = document.getElementsByName('element');
var others = document.getElementsByName('other');
var compare = function(choice1, choice2) {
if (choice1 == "1") {
if (choice2 == "2") {
alert ("Pokem8 wins");
}
}
else if (choice2 == "1") {
if (choice1 == "2") {
alert ("Other guy wins");
}
}
else {
alert ("rofl so noob neither wins");
}
}
document.getElementById('fight').onclick = function() {
compare(ele, others);
};
请帮忙解决这个问题。我试着寻找一个答案,尝试了许多不同的变体等等。我好像修不了。请帮忙:3
jsfiddle链接
这是因为getElementsByName返回一个HTMLCollection。所以你必须使用:
var ele = document.getElementsByName('element')[0].value;
var others = document.getElementsByName('other')[0].value;
var compare = function (choice1, choice2) {
if (choice1 == 1) {
if (choice2 == 2) {
alert("Pokem8 wins");
}
} else if (choice2 == 1) {
if (choice1 == 2) {
alert("Other guy wins");
}
} else {
alert("rofl so noob neither wins");
}
};
document.getElementById('fight').onclick = function () {
compare(ele, others);
};
演示这是因为getElementsByName
返回HTMLCollection
的类数组对象,并且当比较删除字符串只是给数字。所以你必须使用:
var ele = document.getElementsByName('element')[0].value;
相关文章:
- Javascript:selenium Web驱动程序isDisplayed()不工作
- jQuery UI自动完成突然停止工作
- AngularJS UI路由器不能像ng路由器那样工作
- HTML5音频加载和播放获胜'我不能在iPad上工作
- JavaScript打印功能使日历停止工作
- Javascript.getHours()工作不正常
- 为什么这在IE中的工作方式与在Firefox中不同
- 视频HTML没有'无法在Internet Explorer 11上工作
- 扩展移相器按钮类不工作
- Firebase迁移-简单的Firebase.set没有'不再工作了——旧的还是新的
- 谷歌地图不是以HTML显示,而是在JS Fiddle上工作
- 正在尝试使用if和else添加类,但无法正常工作
- Jquery FadeIn FadeOut 只工作一次
- Foreach无法在Typescript中工作
- 另一个ajax调用中的Jquery ajax调用在for循环中没有按预期工作
- 为什么不是't窗口.恢复正常工作吗?(javascript/jquery)
- JS可以在Chrome中工作,但不能在Firefox中工作
- ajaxToolkit PopupControlExtender不工作.过时的
- HTML标记在脚本标记中工作
- javascript扫雷器floodfill算法不能正常工作