【问题标题】:nested function calls on "click" event in javascript [duplicate]javascript中“单击”事件的嵌套函数调用[重复]
【发布时间】:2017-10-07 17:40:23
【问题描述】:

这是我的代码,现在有些人可能会说为什么不在该功能块中包含一行代码,但我不想,我该如何实现。如何在按钮的“单击”事件上调用 this.click 方法

 var i = 0;
function el() {
    this.type = "button",
    this.el = false,
    this.click = function () {
        this.setHtml(i++);
    },
    this.setHtml = function (t) {
        this.el.innerHTML = t;
    }
    fragment = document.createDocumentFragment(),
        element = fragment.appendChild(document.createElement(this.type));
    element.setAttribute("data-el", this.type);
    element.innerHTML = "Default Button";
    this.el = element;
    attachEvent("click", this);
}
// this should be a seperate function ....
function attachEvent(ev, me){
//me doesn't work, but i want it to call the click method
    me.el.addEventListener("click", me.click, false);//....

}


div  = new el();
document.getElementById('areaA').appendChild(div.el);

【问题讨论】:

    标签: javascript function ecmascript-6


    【解决方案1】:

    改变这个:

    me.el.addEventListener("click", me.click, false);//....
    

    到这里:

    me.el.addEventListener("click", me.click.bind(me), false);//....
    

    当您只传递me.click 时,您只是传递了对click 函数的引用,并且与me 的绑定丢失了。 .bind() 将创建一个自绑定存根函数,该函数将在调用事件处理程序时为您提供正确的 this 值。

    【讨论】:

    猜你喜欢
    • 2021-05-12
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    • 2019-09-19
    • 2012-02-07
    相关资源
    最近更新 更多