简体   繁体   English

如何在 Javascript 中显示文本?

[英]How to display text in Javascript?

I have some functions and some variables.我有一些函数和一些变量。 I would like to return a variable and the function outcome as text on my browser.我想在浏览器上以文本形式返回一个变量和函数结果。

What I have done is I have made a HTML file with the text:我所做的是我用文本制作了一个 HTML 文件:

<SCRIPT SRC="rockpaper.js">
</SCRIPT>

And this refers to this javascript file:这是指这个javascript文件:

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
    computerChoice = "Computer chooses rock";
} else if(computerChoice <= 0.67) {
    computerChoice = "Computer chooses paper";
} else {
    computerChoice = "Computer chooses scissors";
}

console.log(computerChoice);

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

    if(choice1==="Computer chooses rock")
    {
        if(choice2==="scissors")
        {
            return("rock wins");
        }
            else
            {
                return("paper wins");
            }
    }
    if(choice1==="Computer chooses paper")
    {
        if(choice2==="rock")
            return("paper wins");
            else
            {
                return("scissors wins");
            }
    }
    if(choice1==="Computer chooses scissors")
    {
        if(choice2==="rock")
        {
        return("rock wins");
        }
        else
        {
            return("scissors wins");
        }
    }
}

console.log(compare(computerChoice,userChoice))

However, when I open it with a browser, the text doesn't display, but the prompt does.但是,当我用浏览器打开它时,文本不显示,但提示显示。

It works fine in Codecademy, though.不过,它在 Codecademy 中运行良好。

Nothing being displayed on the page is normal behaviour seeing as you have not told the browser to do so.页面上没有显示任何内容是正常行为,因为您没有告诉浏览器这样做。

Maybe you want something like this.也许你想要这样的东西。

document.body.innerHTML = compare(computerChoice, userChoice);

Basically, this set's the HTML of the body to value and removes anything currently in the body, or基本上,这个集合是要评估并删除当前正文中的任何内容的正文的 HTML,或者

var generatedText = compare(computerChoice,userChoice), // 1
    myText = document.createTextNode( generatedText );  // 2
document.body.appendChild( myText );                    // 3

Will on line 1 get the generated value and save it, on line 2 will create a text element on the document and on line 3 it will append the text element/node to the end of the body.将在第1行获取生成的值并保存它,在第2行将在文档上创建一个文本元素,在第3行它会将文本元素/节点附加到正文的末尾。

This way nothing is removed from the document.这样就不会从文档中删除任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM