如何在 Javascript 中显示文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20309539/
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
How to display text in Javascript?
提问by Paze
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 中运行良好。
回答by iConnor
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 1get the generated value and save it, on line 2will create a text element on the document and on line 3it will append the text element/node to the end of the body.
将在第1行获取生成的值并保存它,在第2行将在文档上创建一个文本元素,在第3行它将文本元素/节点附加到正文的末尾。
This way nothing is removed from the document.
这样就不会从文档中删除任何内容。