为了账号安全,请及时绑定邮箱和手机立即绑定

需要帮助了解类中创建的 DOM 元素和对象之间的关系

需要帮助了解类中创建的 DOM 元素和对象之间的关系

芜湖不芜 2022-09-16 21:28:15
class Button {    constructor(name) {        this.target = 'bullseye';        this.name = name;        this.element = this.create();    }    create() {        var button_html = '<div>'+this.name+'</div>';        var button_element = $(button_html);        button_element[0].addEventListener('click', function(e) {            Button.yell('??????');            //Should be buttonA, or buttonB depending on which one was clicked. I have tried, (this) & (e), but to no success.        });         $('body').append(button_element);        return button_element;    }    static yell(element){        alert('You have hit the '+element.target);    }}let buttonA = new Button('Button A');let buttonB = new Button('Button B');https://jsfiddle.net/x4dsgp5b/1/我觉得我在这里误解了一些非常基本的东西。将[可单击]按钮放置在类的主体上并与按钮A或按钮B(取决于单击哪个)进行交互的正确语法/逻辑是什么?
查看完整描述

4 回答

?
回首忆惘然

TA贡献1847条经验 获得超11个赞

可以仅使用名称,并使用属性来获取当前按钮。

然后在单击处理程序中,您通过名称知道单击了哪个按钮。this


像这样:


class Button {

    constructor(name) {

        this.name = name;

        this.element = this.create();

    }

    

    create() {

        const element = document.createElement("button"); 

        element.innerHTML = `<div>${this.name}</div>`;

        element.addEventListener('click', this.yell.bind(this))

       

        document.body.appendChild(element);

        

        return element;

    }


    yell() {

        alert('You have hit the '+this.name);

    }

}


const buttonA = new Button('Button A');

const buttonB = new Button('Button B');

一些注意事项:

  • 我使用了新的ES6同轴(不需要时没有var或让)

  • 我没有使用 jquery(这个例子很容易在纯 JavaScript 中完成)

  • 我用作点击的直接处理程序,为了有好的我必须绑定它this.yellthis

  • 我需要 yell 函数中的属性才能知道名称,这就是我删除 static 关键字的原因。this


查看完整回答
反对 回复 2022-09-16
?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

我相信有一个更优雅的解决方案,但这个有效。


class Button {

    constructor(name) {

        this.target = 'bullseye';

        this.name = name;

        this.element = this.create();

    }

    create() {

        var buttone = document.createElement("div");

        buttone.innerHTML = this.name;

    

        document.body.appendChild(buttone);

        let _name = this.name;

        buttone.addEventListener('click', function(e) {

            Button.yell(_name);

        }); 

        

        return buttone;

    }


    static yell(element){

        alert('You have hit the '+element);

    }



}


let buttonA = new Button('Button A');

let buttonB = new Button('Button B');


查看完整回答
反对 回复 2022-09-16
?
湖上湖

TA贡献2003条经验 获得超2个赞

这应该有效!您已经有一个接受该元素的函数 (按钮.yell)。

button_element[0].addEventListener('click', Button.yell);


查看完整回答
反对 回复 2022-09-16
?
元芳怎么了

TA贡献1798条经验 获得超7个赞

我对此的理解是,您希望警报说出“按钮A”或“按钮B”一词。


button_element[0].addEventListener(

     'click', 

     (e) => Button.yell(this.name)

);

请注意,我使用的是箭头函数语法 ()而不是函数语法。这样做的原因是,如果使用函数语法,则处理程序函数中的值将不同。=>this


查看完整回答
反对 回复 2022-09-16
  • 4 回答
  • 0 关注
  • 93 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信