[英]How I can show a Variable Valor in to a h1 in html and js
我是编码的新手,我想学习很多东西,所以我找到了 Stackoverflow 来解决我的问题......
我的代码是:
<h1 class="Result" id="result">0</h1>
现在,我做了一个基本的 JS 文件:
const number = 0;
var elem = document.getElementById('result');
而且,现在我不知道该怎么做,将它显示在 h1 中,如果有人可以帮助我,我将不胜感激。
这些是您可以动态添加值的一些方法。
document.getElementById('result').innerHTML = number;
document.getElementById('result').innerText = number;
document.getElementById('result').textContent = number;
你有一个 id 为“result”的 h1,旁注总是有不同的 id 和类名,所以你不要混淆自己。
<h1 class="Result" id="result">0</h1>
对于您的 javascript:
var elem = document.getElementById('result')
因此,现在您已将 h1 的内容放在变量中,您可以使用以下方法显示它:
console.log(elem)
您的代码不起作用的原因是您没有使用变量的 console.log 来显示变量内的内容。
首先,您需要像您一样使用 document.getElementById() 方法获取 h1 标签。
比您使用 innerHTML 属性来显示文本。
这是完整的代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
javaScript example
</title>
</head>
<body>
<button onclick="myFunction()">
click to see message
</button>
<h1 Id="message" class="message">
</h1>
<script>
function myFuntion(){
var message = "hello, how are you\?";
document.getElementById("message").innerHTML = message;
}
</script>
</body>
</html>
First we created a button that has a function attach to it, than we create an function that will store the message. When the button is clicked, the message will show in the h1 tag.
Good luck!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.