Javascript 如何在一个元素中添加多个带有选择器的事件侦听器?

Javascript 如何在一个元素中添加多个带有选择器的事件侦听器?,javascript,dom,Javascript,Dom,这是我现在拥有的 我试图将现有的Jquery代码转换成纯JS var todoList = document.getElementById('todo-list'); todoList.addEventListener('change',this.toggle.bind(this),true); todoList.getAttribute('.toggle'); todoList.addEventListener('dblclick', this.edit.bind(this),tr

这是我现在拥有的 我试图将现有的Jquery代码转换成纯JS

var todoList = document.getElementById('todo-list');
  todoList.addEventListener('change',this.toggle.bind(this),true);
  todoList.getAttribute('.toggle');
  todoList.addEventListener('dblclick', this.edit.bind(this),true);
  todoList.getAttribute('label');
  todoList.addEventListener('keyup', this.editKeyup.bind(this),true);
  todoList.getAttribute('.edit');
  todoList.addEventListener('focusout', this.update.bind(this),true);
  todoList.getAttribute('.edit');
  todoList.addEventListener('click', this.destroyCompleted.bind(this),true);
  todoList.getAttribute('.destroy');

这工作正常,您可以在这里运行并检查它

mousemove=()=>console.log('mousemove');
dblclick=()=>console.log('dblclick');
单击=()=>console.log('click');
var todoList=document.getElementById('todo-list');
todoList.addEventListener('dblclick',dblclick.bind(this),true);
todoList.addEventListener('click',click.bind(this),true);
todoList.addEventListener('mousemove',mousemove.bind(this),true)

我认为您试图做的是事件委派,要在vanilla JS中完成这项工作,您需要自己编写一个小函数

HTMLElement.prototype.on=函数(事件、选择器、处理程序){
此.addEventListener(事件,函数(e){
设target=e.target;
if(类型(选择器)==“字符串”){
而(!target.matches(选择器)&&target!==此){
target=target.parentElement;
}
if(target.matches(选择器))
调用(target,e);
}否则{
选择器。调用(this,e);
}
});
};
然后,您可以使用它来处理事件。我没有您的标记或您正在调用的函数,但这应该可以做到

HTMLElement.prototype.on=函数(事件、选择器、处理程序){
此.addEventListener(事件,函数(e){
设target=e.target;
if(类型(选择器)==“字符串”){
而(!target.matches(选择器)&&target!==此){
target=target.parentElement;
}
if(target.matches(选择器))
调用(target,e);
}否则{
选择器。调用(this,e);
}
});
};
const todoList=document.getElementById('todo-list');
todoList.on('change','.toggle',this.toggle.bind(this));
todoList.on('dblclick','label',this.edit.bind(this));
todoList.on('keyup','.edit',this.editKeyup.bind(this));
todoList.addEventListener('focusout','.edit',this.update.bind(this));

todoList.addEventListener('click','.destroy',this.destroy completed.bind(this))它不工作吗?不,我不知道为什么。我这里有jquery代码示例$('#todo list')。on('change','toggle','this.toggle.bind(this))。on('dblclick','label','this.edit.bind(this))。on('keyup','edit','this.editKeyup.bind(this))。on('focusout','edit','this.update.bind(this))。on('click','destroy','this.destroy.bind(this));},您试图做的是所谓的事件委派,它被烘焙到jquery中,在vanilla JS中不容易完成,所以您的混淆是有意义的;-)我很惊讶这个能起作用。但是我的代码仍然不起作用。请尝试这种方式,而不是调用
this.functionname.bind(this)
,只需调用
functionname.bind(this)
,为什么您只是获取
getAttribute(X)
而根本不使用它?您从jquery代码到javascript的转换是错误的。在这里签出jQueryAPI。
on()
的第二个参数是选择器,但在转换后的代码中没有这样做。我的函数在主对象中。感谢这位朋友,我将首先研究这个参数,并将其应用到我的代码中。祝你过得愉快。没问题!如果你真的成功了,请把我的答案也投上一票;-)它起作用了。太棒了,这种东西对我很有帮助,因为我还是个初学者