如何在用户单击图像时清除页面并计算输出

How to clear a page on user clicking a image and calculate output

本文关键字:计算 输出 清除 用户 单击 图像      更新时间:2023-09-26

我正在制作一个石头剪刀布网站,我已经制作了一个带有三张图片的网页JSFIDDLE DEMO在这里!我想在点击图像时调用一个函数它会清除网页显示电脑的选择并显示用户是否获胜我要使用的javascript代码是

var computerChoice = Math.random();
if (computerChoice < 0.34) {
    computerChoice = "rock";
} else if(computerChoice <= 0.67) {
    computerChoice = "paper";
} else {
    computerChoice = "scissors";
} console.log("Computer: " + computerChoice);
var compare=function(choice1,choice2)
{
    if(choice1==choice2){
        return "The result is a tie!";
    }
    if(choice1=="rock")
    {
        if(choice2=="scissors")
        {return "rock wins";}
        else if(choice2=="paper")
        {return "paper wins";}
    }
    if(choice1=="paper")
    {
        if(choice2=="scissors")
        {return "scissors wins";}
        else if(choice2=="rock")
        {return "paper wins";}
    }
 if(choice1=="scissors")
    {
        if(choice2=="paper")
        {return "scissors wins";}
        else if(choice2=="rock")
        {return "rock wins";}
    }
};
compare(userChoice,computerChoice);

这是一个可以让你开始的小提琴- fiddle

我会想一个不同的方法,用数字代替文本,这可能会缩短代码,但这将花费我一两天的时间。

    $( 'img' ).on('click', function(){
  var userChoice = this.id;
  var computerChoice = Math.random();
    if (computerChoice < 0.34)
       {
        computerChoice = "rock";
        }
         else if(computerChoice <= 0.67)
       {
        computerChoice = "paper";
        }
         else
       {
        computerChoice = "scissors";
        }
        console.log("Computer: " + computerChoice);
  compare(userChoice,computerChoice);
//---------------------------------------------------
});
var compare=function(choice1,choice2)
{
    if( choice1==choice2 )
    {
        return "Tie!";
     }
    if( choice1=="rock" )
    {
     if(choice2=="scissors")
        {
          $('.putmehere').html( "rock wins" );
         }
        else if(choice2=="paper")
        {
         $('.putmehere').html( "paper wins" );
         }
     }
    if(choice1=="paper")
      {
       if(choice2=="scissors")
         {
          $('.putmehere').html( "Scissors wins" );
          }
          else if(choice2=="rock")
         {
          $('.putmehere').html( "rock wins" );
         }
          }
     if(choice1=="scissors")
       {
        if(choice2=="paper")
        {
         return $('.putmehere').html( "scissors wins" );
         }
         else if(choice2=="rock")
        {
         $('.putmehere').html( "rock wins" );
         }
        }
};