0

我有以下代码,并想从使用 live() 方法更改为使用 on() 方法:

$('.commenttext').live('keydown', function(e) {
    if ((e.which == 13) && !e.shiftKey) {
        comment($(this));
        return false;
    }
});

它是关于评论一篇文章 - 也是使用 on() 方法动态创建的一篇文章。如果我像这样仅将“live”一词更改为“on”

$('.commenttext').on('keydown', function(e) {
    if ((e.which == 13) && !e.shiftKey) {
        comment($(this));
        return false;
    }
});

那么它只适用于不是即时创建的项目。

更新 1

我将代码更改为以下内容:

$('.commentsDiv').on('keydown', '.commenttext', function(e) {
    if ((e.which == 13) && !e.shiftKey) {
        comment($(this));
        return false;
    }
});

commentsDiv 是 commenttext 的父元素,但它仍然不适用于动态创建的元素。例如,以下函数动态创建 commentsDiv:

$('#postDiv').on('keydown', '#posttext', function(e) {
    if (e.which==13 && !e.shiftKey) {
        post($(this));
        return false;
    }
});

有谁知道如何正确调整?

谢谢 :)

4

4 回答 4

2

live表单实际上是一个使用 的委托document,因此新格式为:

$(document).on('keydown', '.commenttext', function...);

通常,最好使用.commenttext不随内容变化的选择器的更接近一致的父级(在这种情况下),但document应该适用于大多数情况。

于 2012-05-05T22:23:16.400 回答
2

您需要将回调附加到 .commenttext 静态父级的静态意味着页面加载时存在。

例子:

$('body').on('keydown', '.commenttext', function(e) {
    if ((e.which == 13) && !e.shiftKey) {
        comment($(this));
        return false;
    }
});

或者:

$('{staticParentElement}').on('keydown', '.commenttext', function(e) {
    if ((e.which == 13) && !e.shiftKey) {
        comment($(this));
        return false;
    }
});
于 2012-05-05T22:32:47.857 回答
1

您可以使用最近的静态父元素作为事件持有者。但是,您也可以使用body

$('body').on('keydown', '.commenttext', function(e) {
    if ((e.which == 13) && !e.shiftKey) {
        comment($(this));
        return false;
    }
});
于 2012-05-05T22:22:34.850 回答
1
$('parentElement').on('keydown', '.commenttext', function(e) {
    if ((e.which == 13) && !e.shiftKey) {
        comment($(this));
        return false;
    }
});

将“parentElement”替换为 .commenttext 的父元素。

于 2012-05-05T22:23:02.917 回答