所以我有一个脚本 block :
<script>
var totalPopulation = 0;
for(xxxxx){
totalPopulation = totalPopulation + xxx
}
</script>
<tr>
<input type="text" name="censusPop" value=totalPopulation/>
<tr>
我对 JavaScript 还很陌生。但是有没有办法将脚本 block 中的变量值分配给 HTML 元素(例如输入类型)?我知道代码无法访问。
最佳答案
希望它能帮助您了解 JavaScript 的工作原理
<html>
<head>
<script>
var totalPopulation = 0;
function addAndShowPopulation(population) {
totalPopulation = totalPopulation + population;
var input_tag = getTag('my_input_id');
input_tag.value = totalPopulation;
}
function startAdding() {
addAndShowPopulation(10);
setTimeout( function(){startAdding();},1000);
}
function getTag(id) {
return document.getElementById(id);
}
</script>
</head>
<body onload="startAdding();">
<div>
<input type="text" id="my_input_id" name="censusPop" value="" placeholder="Total Population"/>
</div>
</body>
</html>
关于javascript - html脚本变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19709381/