这是从以下已解决的问题中解脱出来的(所以请不要将其标记为重复):
我在数据表中创建了一个动态文本框。现在,我需要访问该值以在按键时计算新值。虽然我发现(Event binding on dynamically created elements?)的答案非常有用,但我仍然迷失了如何获得文本框的价值。
"密钥更改"由于我收到警报,因此已触发功能。但是,我正在寻找一个NaN' (不是数字)值。请帮忙!
这是我的代码:
var xindex;
var yindex;
$(document).on('mouseover', '#table1 tr', function() {
xindex = this;
yindex = this.rowIndex;
});
var dtable = $('#table1').DataTable();
var origval = $('#table1 tr:eq(' + parseInt(yindex) + ') >td:eq(' + 1 + ')').html();
//this is the original value in which I would like to add the adjustment
var textvalue = $(yindex).find(".txtval");
//upon creating the datatable dynamically, the class of the input textbox is "txtval"
var newval;
$(document).on('keypress', '.textvalue', function(e) {
if (e.which != 8 && e.which !=0 && (e.which < 48 || e.which > 57)){
e.stopImmediatePropagation();
return false;
}
}).on('keyup change', function(e) {
newval = origval + this.value;
alert(newval);
});
答案 0 :(得分:0)
在您的函数中,this
是文档。如果你想要文本框中的文本,那么this.value就没有了。
这是我的Chrome控制台:
$(document).on('keypressed', 'body', function (e) {
return false
}).on('keyup change', function(e) {
console.log(this) });
返回[document]
答案 1 :(得分:0)
幸运的是,我能够通过全局声明变量(并在数据表鼠标悬停事件上插入值)来解决问题。请看下面的代码(如果你可以帮我改进/清理代码,我恳请你,请这样做。谢谢你)
var xndex;
var yindex;
var origval;
var newval;
$(document).on('mouseover', '#table1 tr', function() {
rndex = this;
jindex = this.rowIndex;
origval = $('#table1 tr:eq(' + parseInt(yindex) + ') >td:eq(' + 1 + ')').html();
});
$(document).on('keypress', '.txtval', function(e) {
var mvalue = jQuery(xndex).find(".txtval").val();
//value to be added to origval
if (e.which != 8 && e.which !=0 && (e.which < 48 || e.which > 57)){
e.stopImmediatePropagation();
//to trap non-numeric characters
return false;
}).on('keyup change', function(e) {
newval = parseFloat(origval) + parseFloat(mvalue);
alert(newval);
});