嗨,我将 fName、lName 和位置设置为空字符串,我希望在单击按钮后更改它们的值并将该值保存到 this.templates ${this.fName} 等。
showMessage 方法应该接收点击并更新值并注入模板。除了更新值之外,一切都很好。当它到达“mP.innerHTML = _this.template;”时 行的值是空的,就像在开始时设置的一样。
奇怪的是在“mP.innerHTML = _this.template;”之前运行的 console.log(_this.fName) 点击时给出正确的值。
可能是什么问题呢?我该如何解决这个问题?
class Message {
constructor() {
this.fName = '';
this.lName = '';
this.position = '';
this.bride = {
fName: 'Anna',
lName: 'Doe',
position: 'bride'
};
this.groom = {
fName: 'John',
lName: 'Doe',
position: 'groom'
};
this.template = /*html*/`
<div class="message message-show">
<div class="message-close">x</div>
<h1>
My name is ${this.fName} ${this.lName}, ${this.position}
</h1>
</div>`;
this.elements = function() {
let messageButtons = document.querySelectorAll('.wed-couple-newlyweds-message');
let messagePopup = document.querySelector('.message-popup');
let messageClose = document.querySelector('.message-close');
let messageDiv = document.querySelector('.message');
return {
messageButtons: messageButtons,
messagePopup: messagePopup,
messageClose: messageClose,
messageDiv: messageDiv
};
};
//Initiate Methods
//End of Methods.
}
//declare methods
// 1. show message on click.
showMessage() {
var _this = this;
let els = new this.elements();
let mB = els.messageButtons;
let mP = els.messagePopup;
let mD = els.messageDiv;
mB.forEach(function(message) {
message.onclick = function() {
if (message.classList.contains(`wed-couple-newlyweds-message-bride`)) {
console.log('bride')
_this.fName = _this.bride.fName
_this.lName = _this.bride.lName
_this.position = _this.bride.position
console.log(_this.fName)
mP.innerHTML = _this.template;
} else {
console.log('groom')
_this.fName = _this.groom.fName
_this.lName = _this.groom.lName
_this.position = _this.groom.position
console.log(_this.fName)
mP.innerHTML = _this.template;
}
let mC = els.messageClose;
_this.closeMessage();
}
});
};