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


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 交互(取决于单击的按钮(的正确语法/逻辑是什么?

只能使用名称并使用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 synax(不需要时没有 var 或让(
  • 我没有使用jquery(这个例子很简单,可以用纯JavaScript完成(
  • 我使用this.yell作为点击的直接处理程序,为了获得良好的this我必须绑定它
  • 我需要 yell 函数中的this属性才能知道名称,这就是我删除 static 关键字的原因。

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

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');

这应该有效!你已经有一个接受元素的函数(Button.yell(。

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

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

button_element[0].addEventListener(
'click', 
(e) => Button.yell(this.name)
);

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

最新更新