Javascript 是否将on事件添加到e.currentTarget?
我的页面上的各种元素都有“内容可编辑”标签 单击它们时,我会执行以下操作:Javascript 是否将on事件添加到e.currentTarget?,javascript,jquery,Javascript,Jquery,我的页面上的各种元素都有“内容可编辑”标签 单击它们时,我会执行以下操作: $('[contenteditable]').on('click', this.edit); p.edit = function(e) { console.log(e.currentTarget); e.currentTarget.on('keydown', function() { alert("keydown..."); }); }; 我得到的是当前目标,但当我尝试向其添加
$('[contenteditable]').on('click', this.edit);
p.edit = function(e) {
console.log(e.currentTarget);
e.currentTarget.on('keydown', function() {
alert("keydown...");
});
};
我得到的是当前目标,但当我尝试向其添加keydown时,我得到的错误是:
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...");
}
});
您需要在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]”)之后定义p.edit
代码>导致错误,因为在
上声明时,p.edit
不存在
如果您不知道,您正在将p.edit
定义为函数表达式,这意味着您必须在调用它之前对其进行定义。第一个问题是您正在尝试对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...");
});
}
}
你可以谢谢,但是警报没有为我触发。p
是否等于这个,它看起来确实很奇怪?打开控制台并检查errorsUm,是否要确保未附加多个事件?$(此)
不是您认为的那样。。。您刚刚在文档中添加了一个keydown事件。哈哈,您说得对,thx for notice me@epascarello,post updated do it well:)