簡體   English   中英

為什么我的按鈕onclick功能無法正常工作?

[英]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

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);
};

DEMO

這是因為getElementsByName返回HTMLCollection的類似於數組的對象,並且在比較刪除字符串時僅給出數字。 因此,您必須使用:

var ele = document.getElementsByName('element')[0].value;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM