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

您的代码不起作用,因为在执行事件处理程序时动态创建的元素不会包含在 DOM 中。

您的解决方案是事件委托。jQuery 有.on()来做到这一点。

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

您需要指定一个父容器来将事件委托给它的子元素liek#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 回答
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 回答