Changing variable by html button

前端 未结 8 1219
野的像风
野的像风 2021-01-18 00:23

I\'m learning javascript and I decided to create simple Rock, Paper, Scissors game. I want to make it controllable by buttons. So I made this in html:



        
相关标签:
8条回答
  • 2021-01-18 01:05

    var is used for declaring a variable. You don't need to declare user variable again in user function. You just need to assign a value to declared one.

    var user; //declaration
    function user(choice) {
        user = choice; //assignment
    }
    
    0 讨论(0)
  • 2021-01-18 01:09

    The selections should be encased in the quotes, javascript is looking for the variables named paper etc.

    <button onClick="user(rock)">Rock</button>
    <button onClick="user(paper)">Paper</button>
    <button onClick="user(scissors)">Scissors</button>
    
    0 讨论(0)
  • 2021-01-18 01:12

    The var keyword used in the scope of a function will declare a new local variable.

    Hence, in the global scope, user retains the value "none".

    0 讨论(0)
  • 2021-01-18 01:18

    One problem:

    var user = "none";
    function user(choice){
        var user = choice;
    }
    

    One variable of user is hiding the other variable of user.

    And having a function and variable with the same name is a BAD idea.

    0 讨论(0)
  • 2021-01-18 01:21
    <div id="game">
        <button onClick="choose('rock')">Rock</button>
        <button onClick="choose('paper')">Paper</button>
        <button onClick="choose('scissors')">Scissors</button>
        <div id="result"></div>
        <br>
        <br>
        <button onClick="test()">DEBUG</button>
    </div>
    

    and

    var user;
    function choose(choice){
        user = choice;
    }
    
    function test(click){
        alert("You chose " + user);
    }                         
    
    0 讨论(0)
  • 2021-01-18 01:26

    Seems like a scoping issue. Try removing the var inside the function.

    0 讨论(0)
提交回复
热议问题