如何使用带有jQuery或JavaScript的按钮刷新变量

时间:2016-10-17 20:12:04

标签: javascript jquery

JSFiddle版本没有工作,所以我添加了一个codepen  Working Codepen

我对JavaScript和jQuery相当新,所以如果我的措辞不太正确或者答案非常明显我很道歉,我在这里学习:)所以我建立了一个石头剪刀游戏,除了我的“新游戏”按钮,一切都很棒。我无法弄清楚如何刷新变量'computerChoice'。我已经能够设置它以便页面刷新,但这不是我想要实现的。我想要它,这样当你点击'新游戏'时,变量'computerChoice'将根据随机数选择一个新选项,就像刷新页面时一样。当你点击“新游戏”时我已经尝试将其设置为null但是当你去玩游戏时它只返回数字。

HTML:

<h1>Rock Paper Scissors</h1>
<h2>Pick your weapon!</h2>
<p><button id="refresh">New Game</button></p>
<button onClick='choose("rock")' class="choices">Rock</button>
<button onClick='choose("paper")' class="choices">Paper</button>
<button onClick='choose("scissors")' class="choices">Scissors</button>
<p><button onClick='compare(user, computerChoice)' class="compares">1...2...3...</button></p>
<p><b id="you">...</b> Vs. 
<b id="computer">...</b></p>
<p><b id="results"></b></p>

JavaScript:

//user choices
var user;
var choose = function(choice) {
user = choice;
//document.getElementById("you").innerHTML = user;
}

//computer choices
var computerChoice = Math.random();
if (computerChoice < 0.34) {
  computerChoice = "rock";
} 
else if (computerChoice < 0.67) {
  computerChoice = "paper";
} 
else {
  computerChoice = "scissors";
}

//compare user choice to computer choice
function compare(choice1, choice2) {
if (choice1 === choice2) {
  document.getElementById('results').innerHTML = "How boring, you tied.";
}  
else if (choice1 === "rock") {
  if (choice2 === "scissors") {
    document.getElementById('results').innerHTML = "They'll feel that in the morning.";
} else {
  document.getElementById('results').innerHTML = "Can you breathe? I think not.";
}
}  
else if (choice1 === "scissors") {
if (choice2 === "paper") {
  document.getElementById('results').innerHTML = "Snippitysnip, you sliced them in two.";
} else {
  document.getElementById('results').innerHTML = "Ouch, looking a little blunt.";
}
} 
else if (choice1 === "paper") {
if (choice2 === "rock") {
  document.getElementById('results').innerHTML = "You smothered them, eesh!"
} else {
  document.getElementById('results').innerHTML = "You're looking a bit like a banana split."
}
} 
else {
document.getElementById('results').innerHTML = "Something's not quite right...what did you do?!"
}
}

// refresh, clear and display computer choices and results. Disable, enable buttons.
function disableButtons() {
  $('button.choices').attr('disabled', true);
}

function enableButtons() {
  $('button.choices').attr('disabled', false);
}

$('.choices').click(function() {
  $('#you').html(user); // this works on codepen but not on jsfiddle? D:
  $('#computer').html('...');
  disableButtons();
});
$('#refresh').click(function() {
  $('#results').html('');
  $('#you, #computer').html('...');
  enableButtons();
  refreshComputer();
});
$('.compares').click(function() {
  $('#computer').html(computerChoice);
});

JSFiddle版本没有工作,所以我添加了一个codepen  Working Codepen

3 个答案:

答案 0 :(得分:1)

您的代码看起来不错,但似乎您尝试将vanilla javascript与JQuery混合,并在您的html中添加了一些(不必要的)处理程序,可能是测试您的不同选项的一部分。

我只是稍微重构了一下你的代码,以便在每次点击“1..2..3&#39;按钮,并且它使用JQuery来表示你似乎已经在使用它的所有函数(比如通过JQuery设置html或者使用innerHTML选项,这是你自己的首选项,只需要1个代码库就可以了。所有代码都使用类似的处理方式。

Btw,codepen或jsfiddle很不错,但是这个网站有一个完全有效的片段编辑器,你可以在其中显示它之后的样子;)

&#13;
&#13;
$(function() {
  // click function for choices
  $('.choices').on('click', function(e) {
    var choice = $(e.target).text();
    $('#you').html(choice);
    disableButtons();
  });
  
  // click function for refresh
  $('#refresh').click(function() {
    $('#results').html('');
    $('#you, #computer').html('...');
    enableButtons();
  });
  
  // click function for 1..2..3
  $('#compares').click(function() {
    var computerChoice = getComputerChoice(), user = getUserChoice();
    $('#computer').html(computerChoice);
    compare( user.toLowerCase(), computerChoice.toLowerCase() );
  });
  
  // gets the previously stored userChoice
  function getUserChoice() {
    return $('#you').text();
  }

  // gets a generated computer choice
  function getComputerChoice() {
    var computerChoice = Math.random();
    if (computerChoice < 0.34) {
      computerChoice = "rock";
    } else if (computerChoice < 0.67) {
      computerChoice = "paper";
    } else {
      computerChoice = "scissors";
    }
    return computerChoice;
  }

  //compare user choice to computer choice
  function compare( choice1, choice2 ) {
    var result;
    if (choice1 === choice2) {
      result = "How boring, you tied.";
    } else if (choice1 === "rock") {
      if (choice2 === "scissors") {
        result = "They'll feel that in the morning.";
      } else {
        result = "Can you breathe? I think not.";
      }
    } else if (choice1 === "scissors") {
      if (choice2 === "paper") {
        result = "Snippitysnip, you sliced them in two.";
      } else {
        result = "Ouch, looking a little blunt.";
      }
    } else if (choice1 === "paper") {
      if (choice2 === "rock") {
        result = "You smothered them, eesh!"
      } else {
        result = "You're looking a bit like a banana split."
      }
    } else {
      result = "Something's not quite right...what did you do?!"
    }
    $('#results').html(result);
  }

  // refresh, clear and display computer choices and results. Disable, enable buttons.
  function disableButtons() {
    $('button.choices').attr('disabled', true);
  }

  function enableButtons() {
    $('button.choices').attr('disabled', false);
  }
});
&#13;
body {
  text-align: center;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Rock Paper Scissors</h1>
<h2>Pick your weapon!</h2>
<p>
  <button id="refresh">New Game</button>
</p>
<button class="choices">Rock</button>
<button class="choices">Paper</button>
<button class="choices">Scissors</button>
<p>
  <button id="compares">1...2...3...</button>
</p>
<p><b id="you">...</b> Vs.
  <b id="computer">...</b>
</p>
<p><b id="results"></b>
</p>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

为什么不创建newgame的功能并在其中提供computerChoice的值。 在函数

之前声明变量
"The underlying provider failed on Open."

点击NewGame按钮调用此功能。

var computerChoice = 0

function newgame(){
computerChoice = Math.Random()
}

如果您想要其他内容,请告诉我,我会更新我的回答

答案 2 :(得分:0)

首先,回答你的问题:

你可以刷新&#34;通过将变量转换为计算变量(或换句话说,创建一个每次执行它的函数,生成一个新的随机数并返回它)来更改变量值。请查看下面的代码和computerChoice函数。

继续更详细:你(至少)错误地做了两件事:

  1. jQuery's click method与原生(内联)onClick event handler混合。
  2. 使用内联点击处理程序
  3. 将getElementByID与jQuery元素选择混合
  4. 通常,在项目中添加一个大型库而不使用其方法和工具是没有意义的。

    如果您的项目需要jQuery(可能不是那么简单的程序),最好使用the .on() method,这样可以更灵活地执行event delegation

    您应该删除内联点击处理程序,这是确定的:

    <button class="js-choices">Rock</button>
    <button class="js-choices">Paper</button>
    <button class="js-choices">Scissors</button>
    

    然后使用事件委派将事件处理程序附加到js-choices元素:

    $('body').on('click', '.js-choices', function() {
      choose($(this).text());
    });
    
    function choose(choice) {
      user = choice;
    }
    

    我查看了您的代码并使其正常运行。我看到了以下其他问题:

    1. 你使用了太多if:这几乎总是switch statements的好候选人
    2. 您的条件存在逻辑漏洞(比较Math.random()的值时)
    3. 下面的剪辑并不完美,但它肯定是一种改进:

      &#13;
      &#13;
      var user;
      
      $('body').on('click', '.js-choices', function() {
        user = $(this).text();
        $('#you').html(user);
        $('#computer').html('...');
        disableButtons();
      });
      
      
      //computer choices
      function computerChoice() {
        var temp = Math.random();
        if (temp < 0.34) {
          return "rock";
        }
        if (temp >= 0.34 && temp < 0.67) {
          return "paper";
        } else {
          return "scissors";
        }
      }
      
      //compare user choice to computer choice
      
      // cache your results element to only access it 1 time and improve performance
      // the naming convention says, use a variable with a '$' in front if its
      // a jquery object
      
      var $results = $('#results');
      
      function compare(user, computer) {
        if (user === computer) {
          $results.text("How boring, you tied.");
        } else if (user === "rock") {
          if (computer === "scissors") {
            $results.text("They'll feel that in the morning.");
          } else {
            $results.text("Can you breathe? I think not.");
          }
        } else if (user === "scissors") {
          if (computer === "paper") {
            $results.text("Snippitysnip, you sliced them in two.");
          } else {
            $results.text("Ouch, looking a little blunt.");
          }
        } else if (user === "paper") {
          if (computer === "rock") {
            $results.text("You smothered them, eesh!");
          } else {
            $results.text("You're looking a bit like a banana split.");
          }
        } else {
          $results.text("Something's not quite right...what did you do?!");
        }
      }
      
      // refresh, clear and display computer choices and results. Disable, enable buttons.
      function disableButtons() {
        $('.js-choices').attr('disabled', true);
      }
      
      function enableButtons() {
        $('.js-choices').attr('disabled', false);
      }
      
      $('#refresh').click(function() {
        $('#results').html('');
        $('#you, #computer').html('...');
        computerChoice();
        enableButtons();
      });
      $('.js-play').click(function() {
        compare(user, computerChoice());
        $('#computer').html(computerChoice);
      });
      &#13;
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
      <h1>Rock Paper Scissors</h1>
      <h2>Pick your weapon!</h2>
      <p>
        <button id="refresh">New Game</button>
      </p>
      <button class="js-choices">rock</button>
      <button class="js-choices">paper</button>
      <button class="js-choices">scissors</button>
      <p>
        <button class="js-play">1...2...3...</button>
      </p>
      <p><b id="you">...</b> Vs.
        <b id="computer">...</b></p>
      <p><b id="results"></b></p>
      &#13;
      &#13;
      &#13;