8

私はJavaScriptを学んでいて、簡単なじゃんけんゲームを作成することにしました。ボタンで操作できるようにしたい。だから私はこれをhtmlで作った:

<div id="game">
    <button onClick="user(rock)">Rock</button>
    <button onClick="user(paper)">Paper</button>
    <button onClick="user(scissors)">Scissors</button>
    <div id="result"></div>
    <br>
    <br>
    <button onClick="test()">DEBUG</button>
</div>

そしてこれは.jsファイルにあります。

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

function test(click){
    alert("You chose " + user);
}

だから私はロックボタンをクリックした後、varユーザーをロックに変更すると思いましたが、そうではありません。ロックをクリックしてから[デバッグ]ボタンをクリックすると、「あなたは何も選択しませんでした」というメッセージが表示されます。

4

8 に答える 8

8
<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);
}                         
于 2013-03-16T22:18:24.447 に答える
4

var変数を宣言するために使用されます。user関数で変数を再度宣言する必要はありませんuser。宣言された値に値を割り当てる必要があります。

var user; //declaration
function user(choice) {
    user = choice; //assignment
}
于 2013-03-16T22:14:19.477 に答える
2

1つの問題:

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

ユーザーの1つの変数は、ユーザーの他の変数を非表示にしています。

そして、同じ名前の関数と変数を持つことは悪い考えです。

于 2013-03-16T22:14:21.587 に答える
1

関数のvarスコープで使用されるキーワードは、新しいローカル変数を宣言します。

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

于 2013-03-16T22:16:07.413 に答える
1

Maybe try this.. cleaner markup.. uses jQuery

<div id="game">
    <button class="user" data-name="rock">Rock</button>
    <button class="user" data-name="paper">Paper</button>
    <button class="user" data-name="scissors">Scissors</button>
    <div id="result"></div>
    <br>
    <br>
    <button id="test">DEBUG</button>
</div>


$(document).ready(function() {
    var user = "none";
    $(".user").click(function() {
       user = $(this).attr("data-name");
    });

    $("#test").click(function() {
       alert(user);
    });
});

http://jsfiddle.net/rQDbe/

于 2013-03-16T22:31:46.040 に答える
0

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

于 2013-03-16T22:16:24.403 に答える
0

The other answers are fixing some issues. There is also a problem with the way you're calling the functions as you're passing rock as a variable, you need to use a string:

<button onClick="user('rock')">Rock</button>

Unless you're declaring the variables somewhere but it's not shown in your code.

于 2013-03-16T22:17:19.953 に答える
0

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>
于 2013-03-16T22:19:49.703 に答える