![](/img/trans.png)
[英]Why does e.currentTarget change with jQuery's event delegation?
[英]Adding an on event to an e.currentTarget?
我页面上的各种元素都有内容可编辑标记。
当他们被点击时,我这样做:
$('[contenteditable]').on('click', this.edit);
p.edit = function(e) {
console.log(e.currentTarget);
e.currentTarget.on('keydown', function() {
alert("keydown...");
});
};
我确定当前目标正常,但是当我尝试向其添加keydown时,我得到了err:
Uncaught TypeError: undefined is not a function
这是一个本地DOM元素,您必须将其包装在jQuery中
$(e.currentTarget).on('keydown', function() {
alert("keydown...");
});
e.currentTarget
应该在事件处理程序中等this
,哪个更常用?
很难说这是如何工作的,但我想我会做些类似的事情
$('[contenteditable]').on({
click : function() {
$(this).data('clicked', true);
},
keydown: function() {
if ($(this).data('clicked'))
alert("keydown...");
}
});
第一个问题是您尝试在DOM元素上使用jQuery方法。 第二个问题是,我认为您不想绑定单击的内容,而是内容可编辑元素本身。
在单击时添加事件而不是全局侦听器似乎也很奇怪。 但这是基本思想
$(this) //current content editable element
.off("keydown.cust") //remove any events that may have been added before
.on('keydown.cust', function(e) { //add new event listener [namespaced]
console.log("keydown"); //log it was pressed
});
编辑:我的代码失败。 现在工作正常。
得到您的代码后,我对此进行了改进:
$(function(){
$('[contenteditable]').on('click', function(){
p.edit($(this));
});
});
var p = {
edit: function($e) {
console.log($e);
$e.on('keydown', function() {
console.log($(this));
alert("keydown...");
});
}
}
您可以在jsFiddle上进行检查
您需要在jQuery中包装e.currentTarget(这是一个本地DOM元素),因为“ on”事件是一个jQuery事件:
$(e.currentTarget).on('keydown', function() {
alert("keydown...");
});
编辑:
$('[contenteditable]').on('click', p.edit);
p.edit = function(e) {
$(e.currentTarget).on('keydown', function() {
alert("keydown...");
});
};
您要在$('[contenteditable]').on('click', p.edit);
之后定义p.edit
$('[contenteditable]').on('click', p.edit);
导致错误,因为在声明on
时p.edit
不存在。
如果您不知道, p.edit
定义为函数表达式,这意味着必须在调用它之前对其进行定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.