1

これがシナリオです

$(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() を呼び出しましたが、正常に動作しています。しかし、機能していないのは、キーアップで関数 callThisFunction() を呼び出していないことです。関数が定義されていないというエラーが発生します。しかし、外部jsファイルに同じ関数がある場合、それは正常に呼び出されます。これは、jquery で動的に追加された html コードから関数を呼び出す方法ではありませんか。

私にお知らせください。

ありがとう

4

1 に答える 1

5

問題は、インライン化されたイベント ハンドラーを使用しているため、js エンジンがcallThisFunctionグローバル スコープで関数を検索しますが、関数を dom Ready ハンドラーに追加して、dom Ready ハンドラーのローカル関数にすることで、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);
    }
})
于 2013-10-17T02:34:50.377 に答える