之前我问过这个问题,但是我做得不好,所以自从我编辑以来没有人回复过。无论如何,如果你看下面的Javascript部分,在函数外部声明的变量没有特别说明“未捕获的TypeError:无法读取未定义的属性'p1'”。当我在函数内部移动它们时,它们可以工作。我不明白。我认为通过将其置于功能之外,它们将变得全球化并且可以工作。为什么它在概念上不起作用?当调用该函数时,它是否应该能够获得在函数外声明/创建的变量/属性存在的事实?
HTML
<form name="percent">
<table id="heading">
<tr><td><h2>Enter information here:</h2></td></tr>
<table id="meat">
<tr>
<td>Percentage 1</td>
<td class="denid"><input type="number" name="p1" class="inputB"></td>
<td class="percent1">%</td>
</tr>
<tr>
<td>Denominator 1</td>
<td><input type="number" name="d1" class="inputB"></td>
</tr>
<tr>
<td>Numerator 1</td>
<td><span id="n1"></span></td>
</tr>
<td>Percentage 2</td>
<td class-"denid"><input type="number" name="p2" class="inputB"></td>
<td class="percent1">%</td>
</tr>
<tr>
<td>Denominator 2</td>
<td><input type="number" name="d2" class="inputB"></td>
</tr>
<tr>
<tr>
<td>Numerator 2</td>
<td><span id="2"></span></td>
</tr>
<tr>
<td></td>
<td><input type="button" value="Compute" onclick="calculate()"></td>
</tr>
</table>
的JavaScript
var per1 = document.percent.p1.value;
var den1 = document.percent.d1.value;
var per2 = document.percent.p2.value;
var den2 = document.percent.d2.value;
function calculate () {
var numerator1 = (per1 * den1) / 100;
var numerator2 = (per2 * den2) / 100;
var numeratorT = numerator1 + numerator2;
document.getElementById("numeratorTotal").innerHTML=numeratorT;
var denominatorT = +den1 + +den2;
document.getElementById("denominatorTotal").innerHTML=denominatorT;
var weightedA = (numeratorT / denominatorT) * 100;
document.getElementById("weightedAvg").innerHTML=weightedA + "%";
}
答案 0 :(得分:2)
如果要使用输入字段值初始化全局变量,则应声明它们 标记之后
如下
<html>
<head></head>
<body>
<form>
<!-- your inputs and something something ....-->
</form>
<script>
//your global variables here declared by initializing them with input fields values;
</script>
</body>
</html>
答案 1 :(得分:1)
当您将变量移出函数时它不起作用的原因是因为它们在文档加载时得到一个值设置。要在单击Compute
时获取值,您需要在函数内移动变量。
你可以做的另一件事是在函数外部初始化变量,然后在函数中给它们一个值。
var per1;
var den1;
var per2;
var den2;
function calculate () {
per1 = document.percent.p1.value;
den1 = document.percent.d1.value;
per2 = document.percent.p2.value;
den2 = document.percent.d2.value;
var numerator1 = (per1 * den1) / 100;
var numerator2 = (per2 * den2) / 100;
var numeratorT = numerator1 + numerator2;
document.getElementById("numeratorTotal").innerHTML=numeratorT;
var denominatorT = +den1 + +den2;
document.getElementById("denominatorTotal").innerHTML=denominatorT;
var weightedA = (numeratorT / denominatorT) * 100;
document.getElementById("weightedAvg").innerHTML=weightedA + "%";
}
这样你仍然可以在另一个函数的其他地方使用相同的变量。