Javascript 变量未更新
我有两个文件,我的索引和我的JS文件 在我的索引中,我将有一种形式的输入字段,我的索引文件将链接到我的JS文件 在我的JS文件中,我将有一个变量列表,这些变量将从我的索引文件Javascript 变量未更新,javascript,html,Javascript,Html,我有两个文件,我的索引和我的JS文件 在我的索引中,我将有一种形式的输入字段,我的索引文件将链接到我的JS文件 在我的JS文件中,我将有一个变量列表,这些变量将从我的索引文件input字段中获取它们的值。我计划在一个函数中将我的一些值相乘 在不返回NaN或undefined的情况下执行此操作的正确方法是什么 我一直试图通过将var值onkeyup或onclick设置为“document.getelementbyid”来实现,但它从不返回任何内容 一些示例代码是, HTML 我试过这张支票: va
input
字段中获取它们的值。我计划在一个函数中将我的一些值相乘
在不返回NaN
或undefined
的情况下执行此操作的正确方法是什么
我一直试图通过将var值onkeyup或onclick设置为“document.getelementbyid”来实现,但它从不返回任何内容
一些示例代码是,
HTML
我试过这张支票:
var ServiceLevel = document.getElementById(ServiceLevel).value;
var EstimatedCoreHours = 10;
// Cost Estimate
CostEstimate = ServiceLevel * EstimatedCoreHours;
function CalculateEstimate() {
alert('test = ' +CostEstimate);
// Estimate Cost
parseInt(document.getElementById("PriceEstimate").value=CostEstimate.toFixed(2));
// Estimate Core Hours
parseInt(document.getElementById("EstimatedCoreHours").value=EstimatedCoreHours.toFixed(2));
}
您需要获取javascript中的值。这是你应该做的 创建一个文件index.htm
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<form>
<input id="a1" name="a1">
<input id="a2" name="a2">
<input id="a3" name="a3">
<input type=button onClick='Calculate()'>
</form>
</body>
</html>
var ServiceLevel=document.getElementById(ServiceLevel).value代码>
//ServiceLevel=null
这应该在函数else中,打开此网页时getElementById将给出null
二,
. 您的输入单选按钮具有相同的名称和ID,如果是这种情况,则应使用哪个值,或者它们是单个或组如果缺少一个或多个值,您想做什么?将它们视为0
(这将导致结果0
)?还是拒绝计算?一般来说,您可以使用一元+
运算符轻松地将字符串转换为数字。您的一些示例代码会增加一种味道@*-bleh long day(没关系):)我很好奇你怎么想parseInt(a=b)
因为这是一种算术运算,如果成功,一定会返回“Float”而不是字符串。但是,我可以将值存储在变量中并返回,而无需解析两次。是的,我知道parseFloat
的作用。事实上,做两次似乎很愚蠢。
var ServiceLevel = document.getElementById(ServiceLevel).value;
var EstimatedCoreHours = 10;
// Cost Estimate
CostEstimate = ServiceLevel * EstimatedCoreHours;
function CalculateEstimate() {
alert('test = ' +CostEstimate);
// Estimate Cost
parseInt(document.getElementById("PriceEstimate").value=CostEstimate.toFixed(2));
// Estimate Core Hours
parseInt(document.getElementById("EstimatedCoreHours").value=EstimatedCoreHours.toFixed(2));
}
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<form>
<input id="a1" name="a1">
<input id="a2" name="a2">
<input id="a3" name="a3">
<input type=button onClick='Calculate()'>
</form>
</body>
</html>
function Calculate()
{
var v1 = document.getElementById ("a1").value;
var v2 = document.getElementById ("a2").value;
var v3 = document.getElementById ("a3").value;
var total = GetNumeric (v1) + GetNumeric(v2) + GetNumeric(v3);
}
function GetNumeric(val) {
if (isNaN(parseFloat(val))) {
return 0;
}
return parseFloat(val);
}