问题是由于您使用的是内联事件处理程序,js 引擎将callThisFunction
在全局范围内查找该函数,但是您已在 dom 就绪处理程序中添加了该函数,使其成为 dom 就绪处理程序的本地函数,这将导致 js抛出错误。
解决方案 1. 使函数全局化
//since the function is define outside of dom ready handler it is available in the global scope
function callThisFunction(index, value, count) {
alert('called');
}
$(document).ready(function () {
var rowIndex = 0;
var count = 0;
function dynamicContentAdd() {
rowIndex++;
count++;
var row = "<input name='input[" + rowIndex + "]' onkeyup = 'callThisFunction(" + rowIndex + "," + total[1] + "," + count + ");' id='input" + rowIndex + "' type='text' class='inputfield' />";
$("#table").append(row);
}
})
或者
$(document).ready(function () {
var rowIndex = 0;
var count = 0;
//define the function as a property of the window object again making it available in the public scope
window.callThisFunction = function (index, value, count) {
alert('called');
}
function dynamicContentAdd() {
rowIndex++;
count++;
var row = "<input name='input[" + rowIndex + "]' onkeyup = 'callThisFunction(" + rowIndex + "," + total[1] + "," + count + ");' id='input" + rowIndex + "' type='text' class='inputfield' />";
$("#table").append(row);
}
})
解决方案 2:jQuery 方式 - 使用具有 data-* 属性的委托事件处理程序
$(document).ready(function () {
var rowIndex = 0;
var count = 0;
$('#table').on('keyup', '.myfncaller', function(){
var $this = $(this);
var index = $this.data('index'), value = $this.data('value'), count = $this.data('count');
})
function dynamicContentAdd() {
rowIndex++;
count++;
var row = "<input name='input[" + rowIndex + "]' id='input" + rowIndex + "' type='text' class='inputfield myfncaller' data-index='" + rowIndex + "' data-value='" + total[1] + "' data-count='" + count + "' />";
$("#table").append(row);
}
})