jQuery:live()和delegate()

Kei*_* L. 4 jquery delegatecommand

我将click事件绑定到div元素,该元素是在单击按钮后创建的.我正在使用.live(),这是有效的.我听说,我不应该使用.live,而是.delegate().所以我试过了,但它不起作用,但是.live正在工作.

我的工作jQuery:

$(".myDiv").live("click",function () {
    var Pos = $(this).offset();
    $("#Container").css("left", Pos.left).css("top", Pos.top);
});
Run Code Online (Sandbox Code Playgroud)

不工作的jQuery:

$(".myDiv").delegate("div","click",function () {
    var Pos = $(this).offset();
    $("#Container").css("left", Pos.left).css("top", Pos.top);
});
Run Code Online (Sandbox Code Playgroud)

我的HTML为div

<div class="myDiv"></div>
Run Code Online (Sandbox Code Playgroud)

谁能告诉我,为什么代表不为我工作?

Sin*_*eta 6

截至1.7 .live()已被弃用并.delegate()已被.on()取代

$("body").on("click","div.myDiv",function () { 
    var Pos = $(this).offset(); 
    $("#Container").css("left", Pos.left).css("top", Pos.top); 
});
Run Code Online (Sandbox Code Playgroud)

.on() 现在是超级粘合剂;)

尝试绑定到最接近目标的东西,它肯定会包含它,最好是带有ID的东西:

<div id="mainContent">
    <div class="myDiv"></div><!-- Dynamically created div -->
</div>
Run Code Online (Sandbox Code Playgroud)

这里一个伟大的目标是#mainContent

$("#mainContent").on("click","div.myDiv",function () { 
    var Pos = $(this).offset(); 
    $("#Container").css("left", Pos.left).css("top", Pos.top); 
});
Run Code Online (Sandbox Code Playgroud)