简体   繁体   English

如何使用javascript变量更新HTML中的span元素?

[英]How to update span element in HTML with javascript variable?

I'm trying to update a span element to show my javascript variable is this correct? 我正在尝试更新span元素以显示我的javascript变量是否正确?

 var hometown = "Indianapolis" ; document.getElementById('hometown').innerHTML = 'Indianapolis'; 
 Hometown: <span id="hometown"></span> 

thanks for any help 谢谢你的帮助

It is basically correct except that you never use your variable, so there is no point to the variable. 它基本上是正确的,除非你从不使用你的变量,所以没有指向变量。 If you want to use the variable to change it you can do this instead. 如果要使用变量进行更改,则可以执行此操作。

 var hometown = "Indianapolis"; document.getElementById('hometown').innerHTML = hometown; 
 Hometown: <span id="hometown"></span> 
With this code, you can have a text input that gets set to the variable hometown , like this. 使用此代码,您可以将文本输入设置为变量hometown ,就像这样。

 function update() { var hometown = document.getElementById("text").value; document.getElementById("hometown").innerHTML = hometown; } 
 Hometown: <span id="hometown"></span> <br> <input type="text" id="text"> <input type="button" onClick="update()" value="Update"> 

I know this one is a little complicated, but it works, and it's all your code. 我知道这个有点复杂,但它有效,而且这都是你的代码。

Not completely. 不完全的。 You are not using the variable. 您没有使用变量。

document.getElementById('hometown').innerHTML = hometown;

Since you are not setting html content, using .textContent property is a better option: 由于您没有设置html内容,因此使用.textContent属性是一个更好的选择:

document.getElementById('hometown').textContent = hometown;

Also make sure that element is added to DOM before selecting it, ie put the script after the target span element. 还要确保在选择元素之前将元素添加到DOM,即将脚本放在目标span元素之后。

Hometown: <span id="hometown"></span>
<script> /* JavaScript code goes here */  </script>

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

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