Javascript 事件似乎没有添加到动态生成的文本框 [英] Javascript event doesn't seem to get added to a dynamically generated textbox
问题描述
我在 javascript 中为动态添加的文本框添加了 onkeyup javascript...但它似乎不起作用....
I added onkeyup javascript for a dynamically added textbox in javascript... But it doesnt seem to work....
var cell4 = row.insertCell(3);
cell4.setAttribute('align','center')
var e3 = document.createElement('input');
e3.type = 'text';
e3.name = 'txtqt' + iteration;
e3.id = 'txtqt' + iteration;
e3.onkeyup = totalAmount(event,this,'tblsample');//Adding this lines doesnt work
e3.size = 10;
cell4.appendChild(e3);
但是当我使用
e3.onkeyup = totalAmount;
它有效...这是我的 javascript 函数,
It worked... Here is my javascript function,
function totalAmount(e,obj,tblid){
function totalAmount(e,obj,tblid) {
var tbl = document.getElementById(tblid);
//alert(tbl);
var tblRows = tbl.rows.length;
//alert(tblRows);
var result =0;
var str1;
if (obj != null) {
str1 = obj.id;
} else {
str1 = this.id;
}
var lastChar = str1.substring(5,str1.length);
//alert(lastChar);
if(str1=='txtqt'+lastChar)
{
var str2 = 'txtup'+lastChar;
var str3 = 'txtAmount'+lastChar;
var txtDeduct = document.getElementById(str1).value;
var txtAmt = document.getElementById(str2).value;
var txtTotal = document.getElementById(str3);
var totRes = txtAmt*txtDeduct;
//var res = formatNumber(totRes,2)
txtTotal.value = totRes.toFixed(2)
document.getElementById('txttotAmount').value = totRes.toFixed(2);
for(i=1;i<=tblRows;i++)
{
//alert(tblRows);
txtTotID = 'txtAmount'+i;
if(document.getElementById(txtTotID).value!='')
{
result =parseFloat(result) + parseFloat(document.getElementById(txtTotID).value);
//var res= formatNumber(result,2)
document.getElementById('txtTotalAmount').value = result.toFixed(2);
document.getElementById('txttotAmount').value = result.toFixed(2);
//document.getElementById('txtTotalAmount').value = result;
}
}
}
}
推荐答案
您需要将函数调用包装在匿名函数中:
You need to wrap your function call in an anonymous function:
e3.onkeyup = function(event){ totalAmount(event,this,'tblsample'); }
但是为了实现跨浏览器兼容性,更好的方法是使用 addEvent 函数:
But an even better way to do it, to allow for cross browser compatibility would be to use an addEvent function:
function addEvent(obj,type,fn){
if (obj.addEventListener){
obj.addEventListener(type,fn,false);
} else if(obj.attachEvent){
obj["e"+type+fn]=fn;
obj[type+fn]=function(){
obj["e"+type+fn](window.event);
};
obj.attachEvent("on"+type,obj[type+fn]);
};
};
然后使用该函数添加事件:
And then add the event using that function:
addEvent(e3,'keyup',function(event){ totalAmount(event,this,'tblsample'); });
只是一种更好的处理事件的方式.我建议你改用这种方法.
Just a much better way to handle events. I would recommend you switch to this method.
这篇关于Javascript 事件似乎没有添加到动态生成的文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!