【问题标题】:How do I assign a val onClick如何分配 val onClick
【发布时间】:2015-11-02 15:29:09
【问题描述】:

我正在处理以下内容: http://codepen.io/anon/pen/jPJzZB

HTML:

<h1>Rock, Paper, Scissors, Lizard, Spock</h1><br>
<div id="user-choice">
    <button onClick="userChoice = rock" id="rock"><i class="fa fa-hand-rock-o fa-3x"></i></button>
    <button onClick="userChoice = paper" id="paper"><i class="fa fa-hand-paper-o fa-3x"></i></button>
    <button onClick="userChoice = scissors" id="scissors"><i class="fa fa-hand-scissors-o fa-3x"></i></button>
    <button onClick="userChoice = lizard" id="lizard"><i class="fa fa-hand-lizard-o fa-3x"></i></button>
    <button onClick="userChoice = spock" id="spock"><i class="fa fa-hand-spock-o fa-3x"></i></button>
</div>

CSS:

var choices  =  {rock : {name: "Rock", defeats: {scissors: "crushes", lizard: "crushes"}},
                 paper: {name: "Paper", defeats: {rock:  "covers", spock: "disproves"}},
                 scissors: {name: "Scissors", defeats:{paper : "cuts", lizard: "decapitates"}},
                 lizard: {name: "Lizard", defeats:{paper: "eats", spock: "poisons"}},
                 spock: {name: "Spock", defeats:{scissors : "smashes",rock : "vaporises"}}
                };

var computerChoice = Math.random();
if (computerChoice <= 0.2) {
    computerChoice = "rock";
} else if (computerChoice <= 0.4) {
    computerChoice = "paper";
} else if (computerChoice <= 0.6) {
    computerChoice = "scissors";
} else if (computerChoice <= 0.8) {
    computerChoice = "lizard";
} else {
    computerChoice = "spock";
}



document.write("I chose " + computerChoice + ".");





if(computerChoice == userChoice){
    document.write(" It's a tie...");
}else{
    userChoice = choices[userChoice];    

    var victory = userChoice.defeats[computerChoice] !== undefined;
    computerChoice = choices[computerChoice]

    if(victory) {        
        document.write(" You won! " + userChoice.name + " " + userChoice.defeats[computerChoice.name.toLowerCase()] + " " + computerChoice.name + "!") 
    }else{
        document.write(" I won! " + computerChoice.name + " " + computerChoice.defeats[userChoice.name.toLowerCase()] + " " + userChoice.name + "!");
    }   
}

我不确定如何使用按钮 onClick 来分配变量。 javascript是对此处找到的答案的修改:Rock, Paper, Scissors, Lizard, Spock in JavaScript

【问题讨论】:

    标签: javascript html onclick var


    【解决方案1】:

    这很简单!有两种选择:

    • 在 HTML 中使用内联 JavaScript。

    • 使用 JavaScript DOM API 来完成这项工作。

    选项#1:

    &lt;button onclick="alert('Yeah!!, I was clicked')"&gt;Click me!&lt;/button&gt;

    选项 #2:

    document.getElementById('btn').onclick = function(){
      alert('Yeah!!!, I was clicked');
    }
    &lt;button id="btn"&gt;Click me!&lt;/button&gt;

    请注意,变量赋值与此非常相似,唯一的区别是您应该将警报语句替换为赋值语句。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-07
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      • 2020-08-05
      • 2018-01-08
      相关资源
      最近更新 更多