我有以下代码,希望从使用live()方法改为使用on()方法:
$('.commenttext').live('keydown', function(e) {
if ((e.which == 13) && !e.shiftKey) {
comment($(this));
return false;
}
});它是关于评论一个post -也是一个使用on()方法动态创建的post。如果我只是简单地将"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是注释文本的父元素,但它仍然不能处理动态创建的元素。例如,以下函数动态创建commentsDiv:
$('#postDiv').on('keydown', '#posttext', function(e) {
if (e.which==13 && !e.shiftKey) {
post($(this));
return false;
}
});有没有人知道如何正确调整?
谢谢:)
发布于 2012-05-06 06:23:03
$('parentElement').on('keydown', '.commenttext', function(e) {
if ((e.which == 13) && !e.shiftKey) {
comment($(this));
return false;
}
});将.commenttext的父元素替换为"parentElement“。
https://stackoverflow.com/questions/10466465
复制相似问题