我正在用Javascript做一个基本的剪刀石头布游戏,虽然没有什么新奇的东西,但是我想花一点点时间。我看到的所有内容都只是通过innerHTML以纯文本形式输出了计算机选择的内容,这很好,但是我希望它根据他们选择的内容显示图像。
基本的游戏功能playGame将选择传递给compareChoices函数。而不是将“计算机选择:岩石”传递到我的span id =“ result”中,我想传递一个图像。我一直在阅读有关DOM和节点以及其他内容的信息,但在理解如何在此处应用它方面遇到了困难。
假设我有一个名为rock.gif的图像,当计算机选择“ rock”时,我想将该图像传递给结果跨度。我该怎么做?如果涉及使用DOM而不是使用innerHTML,请帮助我了解和解释一些情况。谢谢!
function playGame(userSelect)
{
userOption = userSelect;
var computerSelection = Math.random();
if (computerSelection < 0.34)
{
computerSelection = "rock";
}
else if (computerSelection <= 0.67)
{
computerSelection = "paper";
}
else
{
computerSelction = "scissors";
}
results = compareChoices(userOption, computerSelection);
document.getElementById("result").innerHTML = "<p>The computer chose " +
computerSelection;
document.getElementById("whoWon").innerHTML = results;
}
function compareChoices(userOption, computerSelection)
{
if (userOption == computerSelection)
{
return "It's a tie!";
}
if (userOption == "rock")
{
if (computerSelection == "scissors")
{
return "You win!";
}
else
{
return "You lose!";
}
} else if (userOption == "paper") {
if (computerSelection == "rock")
{
return "You win!" ;
} else if("scissors") {
return "You lose!" ;
}
} else if (userOption == "scissors") {
if (computerSelection == "rock")
{
return "You lose!";
}else{
return "You win!";
}
}
}
的HTML
<span id="result"></span>
最佳答案
好的,所以我将您的代码缩减为仅我需要的代码。
基本上在页面上放置一个空的图片标签,然后使用javascript设置src。看一下,让我知道是否有您不了解的内容。您必须右键单击并检查图像以查看src,直到您的项目中包含eimage。
user = 0.64;
playGame(user);
function playGame(userSelect) {
userOption = userSelect;
var computerSelection = Math.random();
if (computerSelection < 0.34) {
computerSelection = "rock.gif";
} else if (computerSelection <= 0.67) {
computerSelection = "paper.gif";
} else {
computerSelection = "scissors.gif";
}
document.getElementById("result").innerHTML = "<p>The computer chose " +
computerSelection;
document.getElementById("image").src = computerSelection;
}
<img id="image" src="">
<span id="result"></span>
<span id="whoWon"></span>