簡體   English   中英

從JS發送字符串/結果到HTML頁面

[英]Sending a string/result from JS to HTML-page

我正在研究一個簡單的HTML + JS剪刀石頭布的游戲。

以下是完整的代碼(CSS,JS,HTML): http : //jsfiddle.net/fJw4R/ (我認為在這里過長了)。 在這里,您可以看到帶有圖片的圖片: http : //shinebrightmedia.se/rps/rockpaperscissors.html

如您所見,.math模塊起作用,並且當您選擇岩石,紙張或剪刀時,計算機會隨機選擇一個選項。

但是,我現在想在計算機/顯示器下面放一個文本字符串,我想知道最簡單的方法是什么。 我要它要么說您贏了! 還是你輸了!

我從一個看起來像這樣的函數開始:

function theWinnerIs(userChoice, computerChoice) {

    if (userChoice === computerChoice ) {
        return 'No winner, it is a draw';
    }

    if ((userChoice === 'rock') && (computerChoice === 'scissor')) {
        return 'human';
    }
    if ((userChoice === 'rock') && (computerChoice === 'paper')) {
        return 'computer';
    }

    if ((userChoice === 'paper') && (computerChoice === 'scissor')) {
        return 'computer';
    }
    if ((userChoice === 'paper') && (computerChoice === 'rock')) {
        return 'human';
    }

    if ((userChoice === 'scissor') && (computerChoice === 'rock')) {
        return 'computer';
    }
    if ((userChoice === 'scissor') && (computerChoice === 'paper')) {
        return 'human';
    }

}

將返回值發送到索引文件的最簡單方法是什么? 即。 你贏了! 還是你輸了!

謝謝你的幫助。

無需使用if塊-這是一個非常緊湊的選擇:

var choices = { rock: -1, paper: 0, scissors: 1 };
var score   = choices[userChoice] - choices[computerChoice];
score       = score - (score/2|0) * 3;

...它會給你-1 ,如果用戶丟失了一輪, 1如果他們贏了, 0的平局的情況下。

現在,您可以通過填充其innerHTML屬性將輸出發送到任何准備好的容器:

var results = {
  '-1': 'YOU LOSE',
   '1': 'YOU WIN',
   '0': 'IT\'S A DRAW'   
};
var resultContainer = document.getElementById('result');
resultContainer.innerHTML = results[score];

這是一個小示例,用來說明這兩個概念。

據我了解,您希望根據“ theWinnerIs”方法的結果顯示一些文本。 我建議您在頁面上創建一個div並使用JavaScript設置其內容。 但是,有許多方法可以實現您的目標。

因此,您想將div添加到頁面中,例如<div id="output"></div> 然后,您可以使用以下內容在此處更新文本

var outputElement = document.getElementById("output");
outputElement.innerHTML = theWinnerIs(userChoice, computerChoice);

這是透視圖代碼的更新版本 ,盡管raina77ow的解決方案更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM