JavaScript中的工资计算功能无法正常工作

时间:2017-03-22 06:36:36

标签: javascript html function

通过HTML上的输入,用户输入员工姓名和他们工作的小时数。从这里的提交按钮,它获取信息并将其存储在变量中,以便我可以计算他们的工资量。现在这也是加班费。我认为这是在正确的轨道,但每当我回到我的HTML它显示" undefined"。有什么建议吗?

//Global Variables
var employeeName = document.getElementById("name").value;
var employeeHours = document.getElementById("hours").value;



function paySalary() {
    if (employeeHours <= 40) {
      var regtime = 11.00 * employeeHours;
      var overtime = 0.00;
      var salary = regtime;
    } else if (employeeHours > 40) {
       var regtime = (11.00 * 40);
       var overtime = ((11.00 * 1.5) * (employeeHours - 40));
       var salary = (regtime + overtime);
    }
      document.getElementById("results").innerHTML = "Employee Name: " + employeeName + " | Employee Gross Pay: " + salary;
}

//Event Listener to Submit
var submitButton = document.getElementById("submit");
if (submitButton.addEventListener) {
    submitButton.addEventListener("click", paySalary, false);
} else if (submitButton.attachEvent) {
    submitButton.attachEvent("onclick", paySalary);
}

Screenshot of output

1 个答案:

答案 0 :(得分:0)

查看薪水变量的范围,它在if-else块中定义。通过在函数中声明它来使document.getElementById()可以访问你的工资变量:

<html>
<script>

function paySalary() {
    var employeeName = document.getElementById("name").value;
    var employeeHours = document.getElementById("hours").value;

    if (employeeHours <= 40) {
      var regtime = 11.00 * employeeHours;
      var overtime = 0.00;
      var salary = regtime;
    } else if (employeeHours > 40) {
       var regtime = (11.00 * 40);
       var overtime = ((11.00 * 1.5) * (employeeHours - 40));
       var salary = (regtime + overtime);
    }
    document.getElementById("name").innerHTML = "Employee Name: " + employeeName;
    document.getElementById("pay").innerHTML = "Employee Gross Pay: " + salary;
}

</script>

<body>
<input id="name" value="Kamesh Dashora"></input>
<input id="hours" value=40></input>
<br>
<span id="pay">0</span>
<br>
<button id="submit" onclick="paySalary()">Submit</button>
<body>
</html>