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

时间:2018-08-07 10:35:20

标签: javascript dom

这就是我现在拥有的 我试图将现有的Jquery代码制作为纯JS

(SELECT COUNT(DISTINCT(C2.COURSEFEES))
FROM COURSE C2
WHERE C2.COURSEFEES > C1.COURSEFEES)

2 个答案:

答案 0 :(得分:0)

这很好,您可以在此处运行并检查它。

mousemove = () => console.log('mousemove');
dblclick = () => console.log('dblclick');
click = () => 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);
<div id="todo-list" style="height: 100px; width: 100px; background: yellow;"></div>

答案 1 :(得分:0)

我认为您想做的是事件委托,要在Vanilla JS中进行此工作,您需要自己编写一个小功能。

HTMLElement.prototype.on = function(event, selector, handler) {
  this.addEventListener(event, function(e) {
    let target = e.target;
    if (typeof(selector) === 'string') {
      while (!target.matches(selector) && target !== this) {
        target = target.parentElement;
      }

      if (target.matches(selector))
        handler.call(target, e);
    } else {
      selector.call(this, e);
    }
  });
};

然后可以使用它来处理事件。我没有您的标记或要调用的函数,但这应该可以解决问题!

HTMLElement.prototype.on = function(event, selector, handler) {
  this.addEventListener(event, function(e) {
    let target = e.target;
    if (typeof(selector) === 'string') {
      while (!target.matches(selector) && target !== this) {
        target = target.parentElement;
      }

      if (target.matches(selector))
        handler.call(target, e);
    } else {
      selector.call(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.destroyCompleted.bind(this));