gpt4 book ai didi

javascript - 为什么我的 Javascript 变量没有初始化?

转载 作者:行者123 更新时间:2023-11-30 19:52:27 24 4
gpt4 key购买 nike

我正在尝试构建一个简单的工资计算器,它从基本工资中扣除一定百分比,然后在该输入元素中显示该值,但它不起作用,我不确定哪里出了问题。也许我的变量没有初始化,因为在我运行程序后,当我在控制台中检查变量值时,它说变量未定义。

在调试过程中,值被正确计算,但最终没有放入输入元素。这可能是一个愚蠢的错误,但我已尽我所能,但似乎无法让它发挥作用。任何指导都会有所帮助

function salCal() {
var salary = document.forms[0][6].value;
var utilities = document.forms[0][7].value;
var houseRent = document.forms[0][8].value;
var tax = document.forms[0][9].value;
var totalSalary = document.forms[0][10].value;

if (salary == "") {
window.alert("Basic Salary Missing");
}

utilities = 10 / 100 * salary;
houseRent = 8 / 100 * salary;
tax = 2 / 100 * salary;
totalSalary = salary - (utilities + houseRent + tax);

}
<center>
<h1>Employee Salary Calculator</h1>

<form>
<table>

<tr>
<td>Employee ID</td>
<td> <input type="text" value=""></td>
</tr>

<tr>
<td>Employee Name</td>
<td><input type="text" value=""></td>
</tr>

<tr>
<td>Father Name</td>
<td><input type="text" value=""></td>
</tr>

<tr>
<td>Gender</td>
</tr>

<tr>
<td>
Male
</td>
<td>
<input type="radio" name="gender" checked>
</td>
</tr>
<tr>
<td>
Female
</td>
<td>
<input type="radio" name="gender">
</td>
</tr>

<tr>
<td>CNIC</td>
<td><input type="text" value=""></td>
</tr>

<tr>
<td>Basic Salary*</td>
<td><input type="number" name="sal"></td>
</tr>

<tr>
<td>Utilities*</td>
<td><input type="number" disabled></td>
</tr>

<tr>
<td>House Rent*</td>
<td><input type="number" disabled></td>
</tr>

<tr>
<td>Tax Percentage*</td>
<td><input type="number" disabled></td>
</tr>

<tr>
<td>Total Salary*</td>
<td><input type="number" disabled></td>
</tr>

<tr>
<td>Tax Year</td>
<td>
<select>
<option selected>2014</option>
<option>2015</option>
<option>2016</option>
<option>2017</option>
<option>2018</option>
</select>
</td>
</tr>

<tr>
<td><input type="button" value="Calculate" onclick="salCal()"></td>
<td><input type="button" value="Reset"></td>
</tr>



</table>
</form>
</center>

最佳答案

变量的范围在函数 salCal 内。如果你想在控制台中使用它,请将变量放在全局范围之外

var salary, utilities, houseRent , tax , totalSalary  ;

function salCal() {
salary = document.forms[0][6].value;
utilities = document.forms[0][7].value;
houseRent = document.forms[0][8].value;
tax = document.forms[0][9].value;
totalSalary = document.forms[0][10].value;

if(salary == "") {
window.alert("Basic Salary Missing");
}

utilities = 10/100*salary;
houseRent = 8/100*salary;
tax = 2/100*salary;
totalSalary = salary - (utilities + houseRent + tax);

}

during debugging the values were properly calculated but in the end not put into the input element

您需要将值分配回输入

document.forms[0][10].value = totalSalary ;

关于javascript - 为什么我的 Javascript 变量没有初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54339658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com