使用jquery从动态添加的html代码中调用函数

时间:2013-10-17 02:31:52

标签: javascript jquery html

这是方案

$(document).ready(function(){
 var rowIndex = 0;
 var count = 0;
 function callThisFunction(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);
}

我在点击按钮时调用了函数dynamicContentAdd(),它运行正常。但是没有用的是它没有在keyup上调用函数callThisFunction()。它给出了未定义函数的错误。但是当我在外部js文件中具有相同的功能时,它会成功调用它。这不是从jquery中动态添加的html代码调用函数的方法。

请告诉我。

由于

1 个答案:

答案 0 :(得分:4)

问题是因为你正在使用内联事件处理程序,js引擎将在全局范围内查找函数callThisFunction,但你已经在dom ready处理程序中添加了该函数,使其成为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- * attributes

的委托事件处理程序
$(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);
    }
})