简体   繁体   English

我是否将 Jquery 事件侦听器正确转换为 Javascript? 我不明白 Javascript 如何在不针对 id 的情况下工作?

[英]Did I convert my Jquery event listener into Javascript properly? I don't understand how the Javascript works without targeting the id?

I'm trying to convert jquery into javascript.我正在尝试将 jquery 转换为 javascript。 My app is a simple to do list and I'm targeting a button with an id called #clear-completed.我的应用程序是一个简单的待办事项列表,我的目标是一个 ID 为 #clear-completed 的按钮。 Whenever I click that button on my app, it deletes the completed todo items, but I don't understand where it is being targeting in my new Javascript code.每当我在我的应用程序上单击该按钮时,它都会删除已完成的待办事项,但我不明白它在我的新 Javascript 代码中的目标位置。

Here is the original Jquery code这是原始的Jquery代码

$('#footer').on('click', '#clear-completed', this.destroyCompleted.bind(this));

So I changed it to Javascript and this code worked所以我将其更改为 Javascript 并且此代码有效

var footer = document.getElementById('footer');
      footer.addEventListener('click', this.destroyCompleted.bind(this))

What I don't understand is what happened the the #clear-completed id and how does my new javascript code still work, even though I am not specifying to target the #clear-completed button?我不明白#clear-completed id 发生了什么以及我的新 javascript 代码如何仍然有效,即使我没有指定以#clear-completed 按钮为目标?

Here is the code for the destroyCompleted function这是destroyCompleted function的代码

destroyCompleted: function () {
            this.todos = this.getActiveTodos();
            this.filter = 'all';
            this.render();
        },

In the debugger it runs through the activeTodos function, but I don't see anywhere where the id #clear-completed is targeted?在调试器中,它通过 activeTodos function 运行,但我没有看到 id #clear-completed 的目标位置?

getActiveTodos: function () {
            return this.todos.filter(function (todo) {
                return !todo.completed;
            });
        },
        getCompletedTodos: function () {
            return this.todos.filter(function (todo) {
                return todo.completed;
            });
        },

Did I write my Jquery into Javascript properly?我是否将 Jquery 正确写入 Javascript ? Or did I miss something?还是我错过了什么?

Also, if the id had more than one event listener how would you code that properly?此外,如果 id 有多个事件侦听器,您将如何正确编码? for example例如

$('#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));

The equivalent JavaScript would be:等效的 JavaScript 将是:

document.querySelector('#footer').addEventListener('click', event => {
  const element = event.target.closest('#clear-completed');

  if (
    event.currentTarget !== element && 
    event.currentTarget.contains(element)
  ) {
    this.destroyCompleted(event);
  }
});

The signature $(target).on(event, selector, handler) that you're using is called a delegated event handler, so the handler is invoked on the target element as you have correctly reproduced, but it is only invoked when the event targets an element matching selector which is descendant of target , not including target itself.您正在使用的签名$(target).on(event, selector, handler)称为委托事件处理程序,因此在您正确复制的target元素上调用handler ,但仅在事件发生时调用目标匹配selector的元素,它是target的后代,不包括target本身。

Matching the selector is reproduced above by checking that event.currentTarget .contains() the element returned by event.target .closest(selector) .通过检查event.currentTarget .contains()event.target .closest(selector)返回的元素来匹配选择器。

You could even break this logic out into a helper function to make it more readable:您甚至可以将此逻辑分解为一个帮助程序 function 以使其更具可读性:

document.querySelector('#footer').addEventListener('click', event => {
  const matches = selector => {
    const element = event.target.closest(selector);

    return (
      event.currentTarget !== element &&
      event.currentTarget.contains(element)
    );
  };

  if (matches('#clear-completed')) {
    this.destroyCompleted(event);
  }
});

Since you need this pattern multiple times, it makes sense to move it into another reusable function:由于您多次需要此模式,因此将其移至另一个可重用的 function 是有意义的:

function delegate (target, type, selector, handler) {
  const matches = event => {
    const element = event.target.closest(selector);

    return (
      event.currentTarget !== element &&
      event.currentTarget.contains(element)
    );
  };

  target.addEventListener(type, event => {
    if (matches(event)) {
      handler(event);
    }
  });
}

const element = document.querySelector('#todo-list');

delegate(element, 'change', '.toggle', e => this.toggle(e));
delegate(element, 'dblclick', 'label', e => this.edit(e));
delegate(element, 'keyup', '.edit', e => this.editKeyup(e));
delegate(element, 'focusout', '.edit', e => this.update(e));
delegate(element, 'click', '.destroy', e => this.destroy(e));

You targeted '#clear-completed' in the jquery function by passing the argument,'#clear-completed', to your on event handler.通过将参数“#clear-completed”传递给 on 事件处理程序,您在 jquery function 中定位了“#clear-completed”。 Jquery on says: Jquery 说:

https://api.jquery.com/on/ .on( events [, selector ] [, data ], handler ) https://api.jquery.com/on/.on (事件[,选择器] [,数据],处理程序)

selector Type: String选择器类型:字符串

A selector string to filter the descendants of the selected elements that trigger the event.一个选择器字符串,用于过滤触发事件的选定元素的后代。 If the selector is null or omitted, the event is always triggered when it reaches the selected element.如果选择器为 null 或省略,则始终在到达所选元素时触发事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我将我的 Jquery 反转为 Javascript,但我不明白为什么这种语法有效? - I reversed my Jquery to Javascript, but I don't understand why this syntax works? 我是一个初学者,不了解我的代码是如何工作的(javascript) - I'm a beginner and I don't understand how my code works (javascript) 我不明白这段代码在javascript中的工作方式 - I don't understand how this code works in javascript javascript async await 我不明白它是如何工作的 - javascript async await I don't understand how it works JavaScript - 我不明白这个碰撞检测功能是如何工作的 - JavaScript - I don't understand how this collision detection function works 我不懂的jQuery或javascript语法 - jQuery or javascript syntax that I don't understand 我不明白这个javascript / jquery代码如何执行 - I don't understand how this javascript/jquery codes executes Javascript / JQuery事件参数。 我不明白这个“ e”论点是什么 - Javascript/JQuery event arguments. I don't understand what this 'e' argument is or does 我不明白此代码“如何在javascript中的数组内编写uint32”的工作原理 - I don't understand how this code to “write an uint32 inside an array in javascript” works 我不懂JavaScript中的递归 - I don`t understand recursion in JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM