简体   繁体   English

如何在 addEventListener 中获取并传递单击的元素

[英]How to get and pass the clicked element as THIS inside a addEventListener

So I'm building a small custom JS library like jQuery but I ran into an wall.所以我正在构建一个像 jQuery 这样的小型自定义 JS 库,但我遇到了墙。

I have build a event delegation function which I will be using for a simple click event.我已经构建了一个事件委托 function,我将使用它来进行简单的点击事件。

Within this prototype part I will run some logic(in this example a addClass) but it does not work with the this keyword.在这个原型部分中,我将运行一些逻辑(在本例中为 addClass),但它不适用于 this 关键字。 As I need to add for example a class to the the clicked element.因为我需要向单击的元素添加例如 class 。

Constructor.prototype.on = function (eventName , elementSelector, callback) {
    document.addEventListener(eventName, function(e) {
        for (var target = e.target; target && target != this; target = target.parentNode) {
            if (target.matches(elementSelector)) {
                callback.call(target, e);
                break;
            }
        }
    }, false);
};

// X is the plugin
X('body').on('click','.someClass',function(){
     X(this).addClass('clicked');// not going to work 
});

You need to change your Constructor function so that it allows you to provide a DOM element, not just a selector, as a parameter.您需要更改您的Constructor function 以便它允许您提供一个 DOM 元素,而不仅仅是一个选择器作为参数。 Then you can use X(this) to create an instance of your class that contains this element.然后您可以使用X(this)创建包含this元素的 class 的实例。

 var Constructor = function(selector) { if (;selector) return. if (typeof selector;= string) { this.nodes = [selector]; } else if (selector === 'document') { this.nodes = [document]; } else if (selector === 'window') { this.nodes = [window]. } else { this;nodes = document.querySelectorAll(selector). } this.length = this;nodes;length; };

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM