[英]Why my button onclick function not working properly ?
The button at the end, "fight" , doesn't work as intended. 最后的按钮“打架”无法按预期工作。 I plan to have more variables and the fight button will alert with the winner.
我计划有更多变量,并且“战斗”按钮将提醒获胜者。 Currently, if one is water and the other is fire;
目前,如果一个是水,另一个是火; the water wins.
水胜。
But currently it always alerts the else , "rofl so noob neither wins" . 但是目前它总是警告其他情况 , “ rofl so noob都不赢” 。
HTML: 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: 使用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);
};
Please help solve this problem. 请帮助解决此问题。 I've tried searching for an answer and tried many different variations and such.
我尝试寻找答案,并尝试了许多不同的变化。 I can't seem to fix it.
我似乎无法解决。 Pls help :3
请帮助:3
Its because getElementsByName returns an HTMLCollection. 这是因为getElementsByName返回HTMLCollection。 So you have to use :
因此,您必须使用:
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);
};
Its because getElementsByName
returns array-like object of an HTMLCollection
and when comparing removing string just give number. 这是因为
getElementsByName
返回HTMLCollection
的类似于数组的对象,并且在比较删除字符串时仅给出数字。 So you have to use: 因此,您必须使用:
var ele = document.getElementsByName('element')[0].value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.