javascript 如何在html页面中显示返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17726456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:22:26  来源:igfitidea点击:

How to display a returned value in an html page

javascripthtml

提问by Cherry

I just started learning javascript and followed an exercise on codeacademy to make a text base rock paper scissors game. I wanted to show it to someone, outside of the debug console but I can't figure out how to display it in an html page.

我刚开始学习 javascript,并在 codeacademy 上进行了一项练习,以制作基于文本的剪刀石头布游戏。我想在调试控制台之外向某人展示它,但我不知道如何在 html 页面中显示它。

The code in my html file is:

我的 html 文件中的代码是:

<HTML>

    <HEAD>
        <script src="rockpaperscissors.js"></script>
    </HEAD>

    <BODY>Choose rock, paper or scissors and write your choice in the text box
        <p>
             <A HREF="javascript:processOrder();">Click here to begin</A>
    </p>
    ...
    </BODY>
</HTML>

and the code in my JS is:

我的 JS 中的代码是:

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();

if (computerChoice < 0.34) {
    computerChoice = "rock";
} else if (computerChoice <= 0.67) {
    computerChoice = "paper";
} else {
    computerChoice = "scissors";
}

var compare = function (choice1, choice2) {
    if (choice1 === choice2) return "The result is a tie!";
    if (choice1 === "rock") {
        if (choice2 === "scissors") return "rock wins";
        else return "paper wins";
    }
    if (choice1 === "paper") {
        if (choice2 === "rock") return "paper wins";
        else return "scissors wins";
    }
    if (choice1 === "scissors") {
        if (choice2 === "rock") return "rock wins";
        else return "scissors wins";
    }
};

compare(userChoice, computerChoice);

I get the prompt to choose rock paper or scissors but it does not return anything after that. I don't see the computer choice in the html and I don't know what to use to show it.

我得到提示选择石头纸或剪刀,但之后它没有返回任何东西。我在 html 中没有看到计算机选择,我不知道用什么来显示它。

回答by ejk314

One easy way is to put an element with an idin your html:

一种简单的方法是id在您的 html 中放置一个带有 an 的元素:

<div id="ret"></div>

You can then change the last line of your javascript to:

然后,您可以将 javascript 的最后一行更改为:

document.getElementById("ret").innerHTML=compare(userChoice,computerChoice);

That will put the result inside of that div.

这会将结果放在 that 里面div

Or you could just do:

或者你可以这样做:

document.write(compare(userChoice,computerChoice));

Which will write the result where you put your script tag.

这将写入您放置脚本标记的结果。

回答by seriousdk

You need a place to display the returned result.

您需要一个地方来显示返回的结果。

Change your last line of JS to

将你的最后一行 JS 更改为

alert(compare(userChoice,computerChoice));

回答by uptownnickbrown

Nice job working out the RPS exercise. Take a look at this JSFiddlefor an implementation displaying the user/computer choices and the results.

RPS 练习做得很好。查看此 JSFiddle以获取显示用户/计算机选择和结果的实现。

You'll notice a few key changes. First, you shouldn't link to a javascript function within an href:

您会注意到一些关键的变化。首先,您不应链接到 href 中的 javascript 函数:

<A HREF="javascript:processOrder();">Click here to begin</A>

<A HREF="javascript:processOrder();">Click here to begin</A>

Take a look at this great SO answerfor a variety of ways you can improve upon that practice. In my example implementation, I'm using the jQuery library to create a click event handler on the Click here to beginprompt, like so:

看看这个伟大的 SO 答案,了解您可以改进该实践的各种方法。在我的示例实现中,我使用 jQuery 库在Click here to begin提示上创建一个单击事件处理程序,如下所示:

$('#begin').click(function() {playRPS(); return false;});

$('#begin').click(function() {playRPS(); return false;});

Second, you'll notice the new playRPSfunction. This enables the user to decide when to play your game, and play it multiple times.

其次,您会注意到新playRPS功能。这使用户能够决定何时玩您的游戏,并多次玩它。

With the original code listed above, when the Javascript code is loaded, the browser does a few things right awayand then never again:

上面列出的原代码,当Javascript代码被加载时,浏览器做了几件事情的时候了,然后再也

  • It launches the prompt for the user to input a value. As soon as the user enters their choice:
    • It picks a random value for computerChoice and converts it to the appropriate rock/paper/scissors string value.
    • It executes the compare() function.
  • 它会提示用户输入一个值。一旦用户输入他们的选择:
    • 它为 computerChoice 选择一个随机值并将其转换为适当的岩石/纸/剪刀字符串值。
    • 它执行 compare() 函数。

It doesn't even wait for the user to click your Click here to beginlink! Take a look instead at a function like the following:

它甚至不等待用户点击您的Click here to begin链接!看看下面的函数:

var playRPS = function() {
    var userChoice = prompt("Do you choose rock, paper or scissors?");
    var compChoice = computerChoice();
    var result = compare(userChoice,compChoice);
    $('body').append('<p>You chose ' + userChoice + '</p>')
               .append('<p>The computer chose ' + compChoice + '</p>')
               .append('<p>' + result + '</p>');
};

It's short and sweet. When called (remember, it is called anytime the <a id="begin">link is clicked, as set up with jQuery), it does everything you need to do for a round of RPS:

它简短而甜蜜。当被调用时(记住,它在<a id="begin">链接被点击的任何时候都会被调用,就像用 jQuery 设置的那样),它会做你需要为一轮 RPS 做的一切:

  • It asks the user what they want to choose.
  • It runs the computerChoicefunction, generating a new random number and converting that number to a string.
  • It runs your comparefunction
  • It adds the user's choice, the computer's choice and the result returned by the comparefunction in <p>tags just before the end of the <body>element.
  • 它询问用户他们想要选择什么。
  • 它运行该computerChoice函数,生成一个新的随机数并将该数字转换为字符串。
  • 它运行你的compare功能
  • 它将用户的选择、计算机的选择和compare函数返回的结果添加<p><body>元素末尾之前的标签中。

Now there are any number of ways this could be improved further--the results could be displayed in a prettier way. The user's input should probably be checked to see if it's a valid answer (eg. what happens if I enter "fire" into the box? Or "Paper"?), but this is a great start!

现在有很多方法可以进一步改进——结果可以以更漂亮的方式显示。可能应该检查用户的输入以查看它是否是有效答案(例如,如果我在框中输入“fire”会发生什么?或“Paper”?),但这是一个很好的开始!