JQuery替换.click()中的$(this)导致无法点击的东西?

Lyt*_*yth 0 jquery click this replacewith

我有以下代码:

$('div[class^=locked_]').click(function() {
        var newThis = $(this) ;
        $(this).load(url + " #" + $(this).attr("id"), function() {
            var loaded = $(this).children("#" + $(this).attr("id")) ;
            alert($(loaded).attr("class")) ; // displays "locked_true"
            $(newThis).replaceWith($(loaded)) ;
            alert($(newThis).html()) ;

        }) ;
    }) ;
Run Code Online (Sandbox Code Playgroud)

我不明白我得到的行为:第一个警告显示正确的类(以"locked_"开头).第二个警报显示为null.我不能再次点击相同的按钮,虽然它有合适的类.这是正常的吗?我该怎么办 ?

Ant*_*ist 6

事件处理程序(委托事件除外 - 稍后会详细介绍)直接绑定到元素.如果替换该元素 - 这正是您在使用.replaceWith()函数时所执行的操作 - 您将删除该事件处理程序以及该元素; 你不会将你的事件绑定到新元素.

如前所述,解决方案是事件委派.一般原则是在静态元素上设置一个事件处理程序,该元素将包含动态元素,它将处理事件并负责在事件目标与提供的选择器匹配时执行回调函数.

如果您使用的是jQuery 1.7+,则可以使用该.on()函数执行此操作:

$(document).on('click', 'div[class^=locked_]', function(e) {
    var newThis = $(this) ;
    $(this).load(url + " #" + $(this).attr("id"), function() {
        var loaded = $(this).children("#" + $(this).attr("id")) ;
        alert($(loaded).attr("class")) ; // displays "locked_true"
        $(newThis).replaceWith($(loaded)) ;
        alert($(newThis).html()) ;
    });
});
Run Code Online (Sandbox Code Playgroud)

document在示例中使用过,但理想情况下,您会选择更具体的静态元素(越接近动态元素越好).

如果您没有使用jQuery 1.7+,您可以使用该.delegate()函数获得相同的功能 - 语法实际上是相同的,您只需切换'click''div[class^=locked_]'参数.