如何在javascript中为动态创建的输入框分配onkeypress-function?
你可以在这里找到我的源代码:http://goo.gl/9BHSt
var cell2 = row.insertCell(1);
var el = document.createElement('input');
el.type = 'text';
el.size = "3";
el.name = 'txtUnit' + iteration;
el.id = 'txtUnit' + iteration;
el.onKeyPress = "return checkIt(event)";
cell2.appendChild(el);
el.type = 'text';
el.size = "3";
el.name = 'txtUnit' + iteration;
el.id = 'txtUnit' + iteration;
el.onKeyPress = "return checkIt(event)";
cell2.appendChild(el);
Run Code Online (Sandbox Code Playgroud)
但是
el.onKeyPress = "return checkIt(event)"; 没有用.为什么?
用这个 :
el.onkeypress =
function(event)
{
//write your method body
};
Run Code Online (Sandbox Code Playgroud)
要么
el.onkeypress = KeyPressHandler;
function KeyPressHandler(event)
{
//write your method body
}
Run Code Online (Sandbox Code Playgroud)
编辑
你提供了错误的论点.看到这个:
function KeyPressHandler(event)
{
evt = (evt) ? evt : window.event
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
status = "This field accepts numbers only."
return false;
}
status = ""
return true;
}
Run Code Online (Sandbox Code Playgroud)
你应该将参数名称更改为evt
function KeyPressHandler(evt)
{
evt = (evt) ? evt : window.event
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
status = "This field accepts numbers only."
return false;
}
status = ""
return true;
}
Run Code Online (Sandbox Code Playgroud)
我测试过,它工作正常.
| 归档时间: |
|
| 查看次数: |
8707 次 |
| 最近记录: |