![](/img/trans.png)
[英]Why is my onclick function not working for the button inside a Mustache template?
[英]Why my button onclick function not working properly ?
最后的按钮“打架”无法按预期工作。 我计划有更多变量,并且“战斗”按钮将提醒获胜者。 目前,如果一个是水,另一个是火; 水胜。
但是目前它总是警告其他情况 , “ rofl so noob都不赢” 。
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
这是因为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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.