如何在HTML中使用此JavaScript变量? [英] How do I use this JavaScript variable in HTML?
问题描述
我正在尝试制作一个简单的页面,询问您的名字,然后使用name.length(JavaScript)来确定您的名字有多久.
I'm trying to make a simple page that asks you for your name, and then uses name.length (JavaScript) to figure out how long your name is.
到目前为止,这是我的代码:
This is my code so far:
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length
</script>
<body>
</body>
我不太确定在body标记中应该放什么,以便可以使用我之前声明的那些变量.我意识到这可能是一个真正的初学者水平的问题,但是我似乎找不到答案.
I'm not quite sure what to put within the body tags so that I can use those variables that I stated before. I realize that this is probably a really beginner level question, but I can't seem to find the answer.
推荐答案
您不会在HTML中使用" JavaScript变量. HTML不是一种编程语言,它是一种标记语言,它只是描述"页面的外观.
You don't "use" JavaScript variables in HTML. HTML is not a programming language, it's a markup language, it just "describes" what the page should look like.
如果要在屏幕上显示变量,可以使用JavaScript来完成.
If you want to display a variable on the screen, this is done with JavaScript.
首先,您需要在其中写入以下内容:
First, you need somewhere for it to write to:
<body>
<p id="output"></p>
</body>
然后,您需要更新JavaScript代码以写入该<p>
标记.确保在页面准备好之后 .
Then you need to update your JavaScript code to write to that <p>
tag. Make sure you do so after the page is ready.
<script>
window.onload = function(){
var name = prompt("What's your name?");
var lengthOfName = name.length
document.getElementById('output').innerHTML = lengthOfName;
};
</script>
window.onload = function() {
var name = prompt("What's your name?");
var lengthOfName = name.length
document.getElementById('output').innerHTML = lengthOfName;
};
<p id="output"></p>
这篇关于如何在HTML中使用此JavaScript变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!