所以我有一个脚本块:
<script>
var totalPopulation = 0;
for(xxxxx){
totalPopulation = totalPopulation + xxx
}
</script>
<tr>
<input type="text" name="censusPop" value=totalPopulation/>
<tr>
我对 JavaScript 还很陌生。但是有没有办法将脚本块中的变量值分配给 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>
是的,您只需为输入提供一个 id,例如“id = my_input_id”; 然后,在 javascript 中,只需编写:
$("my_input_id").value=totalPopulation;
这就是 ajax 的工作原理:查找 html 元素 id 并使用 javascript 值动态填充它们。
请注意,html 在 JS 之前读取。如果不是,$("my_input_id") 将返回 Null
更重要的是,你需要做这样的事情:
<tr>
<td>
<input type="text" id="censusPop" name="censusPop" value=""/>
<td>
<tr>
<!-- Other stuff -->
<script>
var totalPopulation = 10;
// or for loop, or whatever here.
var censusText = document.getElementById('censusPop');
censusText.value = totalPopulation;
</script>
</body>
HTML 和 JavaScript 可以交互,但不能直接交互。最好的办法是使用
<script>
标签来设置更新浏览器 DOM 的代码。通过将 <script>
标签放在 HTML 后面(通常位于 <body>
标签的底部),您可以让浏览器有机会在您实际尝试使用元素之前创建它们。
另外注意:
<tr>
标签应该包含<td>
标签,这是行和列的区别。
如果你需要进行多个 DOM 操作,我建议使用 jQuery 是正确的方法。
<tr>
<input id="censusPop" type="text" name"censusPop" value=""/>
</tr>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
// make sure, the code is executed when the DOM is ready
$(function () {
// grab the input element by its ID
var $input = $('#censusPop'),
totalPopulation = 0;
// do your population calculations
totalPopulation = ....;
// assign the value to the input element
$input.val(totalPopulation);
});
</script>