我有一个脚本,我正在与PHP表单一起使用。我正在尝试获取一个计数器字段,我在表单上填写一秒钟后,员工ID字段填写在我的代码下面。
<script type="text/javascript">
var counter = 0;
var timer;
var employee = document.getElementsByName("employeeID")[0];
var employeeVal = document.getElementsByName("employeeID")[0].value;
employee.addEventListener("onchange", startCount);
function countUP () {
counter = counter + 1; //increment the counter by 1
document.getElementsByName("timer_container")[0].value = counter;
}
function startCount () {
timer=setInterval('countUP()', 1000 );
}
function readonly() {
document.getElementsByName("timer_container")[0].readOnly = true;
}
</script>
我尝试过不同的函数来查看事件监听器是否正在触发。我也试过使用不同的事件,onclick,onblur并没有任何运气。我已经采用了计时器功能,并将其设置为直接在HTML上的body标签上加载并且可以正常工作。但是,只要有人将信息输入到员工字段中,我就需要这样做。
答案 0 :(得分:5)
首先,在使用on
时,请勿在事件名称中使用.addEventListener
。 on
前缀仅用于与HTML事件属性的内联事件绑定(这就是<body onload=...>
中适用于您的原因)。内联事件HTML属性 shouldn't be used anymore anyway 。所以,你的行应该是:
employee.addEventListener("change", startCount);
如果您希望在输入数据时触发,请使用input
事件而不是change
事件。
employee.addEventListener("input", startCount);