且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-13 19:32:28

问题在于,由于您正在使用内联事件处理程序,因此js引擎将在全局范围内查找函数callThisFunction,但是您已在其中添加了该函数dom就绪处理程序使其成为dom就绪处理程序的本地函数,这将导致js引发错误.

The problem is since you are using inlined event handlers the js engine will look for the function callThisFunction in the global scope, but you have added the function in the dom ready handler making it a local function to the dom ready handler which will result in the js throwing an error.

解决方案1.将函数设为全局

Solution 1. make the function global

//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- *属性的委托事件处理程序

Solution 2: The jQuery way - Use a delegated event handler with 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);
    }
})