为什么我的按钮onclick功能不能正常工作

Why my button onclick function not working properly ?

本文关键字:常工作 工作 能不能 我的 按钮 onclick 功能 为什么      更新时间:2023-09-26

最后的按钮"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;