0

ランタイムで自動的に作成されるキャンバスを制御したい。ここでの問題はjQuery、ページがready.

$(document).ready(function(ee) {
     $("#containerInsertBtn").click(function(e) {
         e.preventDefault();
         $("#container").html("<canvas width='300' height='300' id='tk'>fall</canvas>");    
    });

    $("#tk").click(function(eg) {
        alert('tic');
    });

});

HTML マークアップ:

<div id="container" contenteditable="true"></div>
<button id="containerInsertBtn">Add Canvas</button>
4

3 に答える 3

3

次のように .on() を使用できます。

$(document).on("click", "#tk", function(eg) {
   alert('tic');
});

また、

$(document).on("click", "canvas", function() {
   console.log( $(this).attr("id") ); //gives you the id of clicked canvas
});

詳細はこちら:: jQuery .on()

于 2013-03-03T05:41:20.490 に答える
0

(他の回答が示唆しているように)を使用するonか、単純なケースでは、要素が存在すると同時にイベントをバインドできます。

readyコールバック内の最上位ですべてのイベントをバインドする必要はありません。

$(document).ready(function(ee) {
    $("#containerInsertBtn").click(function(e) {
        e.preventDefault();
        $("#container").html("<canvas width='300' height='300' id='tk'>fall</canvas>");    

        $("#tk").click(function(eg) {
            alert('tic');
        });
    });
});
于 2013-03-03T05:42:44.797 に答える
0

イベント ハンドラーの実行中に動的に作成された要素が DOM に含まれないため、コードは機能しません。

あなたの解決策はイベント委任です。jQueryには、それを行うための .on()があります。

$("body").on('click', '#tk', function(e) {
    //....
});

イベントをその子要素に委譲するには、親コンテナを指定する必要があります。#tk

タグ名に基づいて要素に委任する場合は、上記と同じです。

$("body").on('click', 'canvas', function(e) {
    console.log($(this)); // you can access the active element by using $(this)
    //....
});
于 2013-03-03T05:45:55.367 に答える