我有这段代码用于以编程方式制作按钮
function makeButton(text, classList, parent, onClick){
let button = document.createElement('button')
button.classList = classList
button.innerHTML = text
button.onclick = onClick
parent.appendChild(button)
return button
}
到目前为止,在我向已实例化的 DOM 元素添加按钮的情况下,它运行良好
let diag = new PopupModal()
makeButton('CANCEL', 'btn btn-sm btn-secondary', diag.footer, function() {
diag.closeFunc()
})
但是我想以一种新的方式使用它,例如在类的构造函数中添加按钮的功能
function makeElement(type, classList, parent){
let el = document.createElement(type)
el.classList = classList
parent.appendChild(el)
return el
}
class complexForm_newProductWithType{
constructor(doc){
this.container = document.createElement('div')
this.container.classList = 'container'
this.doc = doc
this.identifiers = makeElement('div', 'row', this.container)
this.descriptors = makeElement('div', 'row', this.container)
this.options = makeElement('div', 'row', this.container)
this.buttons = makeElement('div', 'row', this.container)
...
this.button_save = makeButton('SAVE', 'btn btn-sm btn-success', this.buttons, function() {
console.log('save')
})
this.button_cancel = makeButton('CANCEL', 'btn btn-sm btn-secondary', this.buttons, function() {
console.log('cancel')
})
}
}
function addForm(doc){
form = new complexForm_newProductWithType(doc)
document.getElementById("doc-selection").innerHTML = form.container.outerHTML
}
在这种情况下,按钮是使用正确的样式和文本创建的,但事件不会触发。我尝试将行
onclick = onClick
更改为 button.addEventListener('click', onClick, false)
但没有效果
我测试了你的基本代码,代码是可以运行的,你能提供控制台信息吗?
function makeButton(text, classList, parent, onClick) {
let button = document.createElement('button');
button.classList = classList;
button.innerHTML = text;
button.onclick = onClick;
parent.appendChild(button);
return button;
};
class FormWithLotsOfButtonsAndInput {
constructor() {
this.diag = document.createElement('div')
document.body.appendChild(this.diag)
this.button1 = makeButton('save', 'btn', this.diag, function () {
console.log('do something')
});
}
}
const _tools = new FormWithLotsOfButtonsAndInput;
console.log(_tools)