简体   繁体   English

如何仅使用 JavaScript 获取单击的按钮的值?

[英]How do I get the value of the button clicked using only JavaScript?

I'm a beginner and I wanted to start building projects and I want to determine the number of rounds using the value of the button the user clicks on.我是一个初学者,我想开始构建项目,我想使用用户单击的按钮的值来确定轮数。

    `<div class="game-type">
        <h2>GAME TYPE</h2>
        <p>choose the number of rounds you'd like to play</p>
        <div class="options">
            <button value="1" type="button">BEST OF 1</button>
            <button value="3" type="button">BEST OF 3</button>
            <button value="5" type="button">BEST OF 5</button>
            <button value="1000" type="button">FREE MODE</button>
        </div>
     </div>

` `

using JavaScript I tried retrieving the value with "this" for the button that is clicked but it doesn't return anything at all.使用 JavaScript 我尝试使用“this”为单击的按钮检索值,但它根本不返回任何内容。 I want to use the value to set the RoundLimit value equal to the button pressed and end the game when RoundCount is equal to the round limit.我想使用该值将 RoundLimit 值设置为等于按下的按钮并在 RoundCount 等于回合限制时结束游戏。

    `const rpsGame = () => {
let playerScore = 0;
let computerScore = 0;
let roundCount = 0;
let roundLimit = 0;

// Universal value
const gameType = document.querySelector(".game-type");


//pick number of rounds to play
const roundNum = () => {
    const roundSelector = document.querySelectorAll(".game-type buttons");
    roundSelector.forEach(roundSelector => {
        roundSelector.addEventListener("click", function () {
            console.log(this);
        });
    });
};
roundNum();`

Im a beginner any criticism is appreciated.我是初学者,任何批评都表示赞赏。 Thank you!谢谢!

it's button instead of buttons它是button而不是buttons

const roundNum = () => {
    const roundSelector = document.querySelectorAll(".game-type button");
    roundSelector.forEach(roundSelector => {
        roundSelector.addEventListener("click", function () {
            console.log(this);
        });
    });
};
roundNum();

and to get the value并获得价值

const roundNum = () => {
    const roundSelector = document.querySelectorAll(".game-type button");
    roundSelector.forEach(roundSelector => {
        roundSelector.addEventListener("click", function (e) {
            console.log(e.target.value);
        });
    });
};
roundNum();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM