我正在编写一个 HTMLElement 并尝试将锚标记动态添加到 html 中。我能够将锚标记添加到 innerHtml (createLink
我的代码中的函数),但缺少 onClick 事件处理程序。如何在 javascript 中附加 onClick 事件处理程序。我正在用打字稿编写我的代码,并使用 babble 和 webpack 转换为 js。
export class MyCustomElement extends HTMLElement {
constructor() {
super();
}
private _serviceResponse: Employee[];
connectedCallback() {
this.getData();
this.innerHTML = '';
}
getData() {
let fetch = window.fetch.bind(window);
fetch('http://localhost/api/v1/values')
.then(response => {
return response.json();
})
.then((data: Employee[]) => {
this._serviceResponse = data;
console.log(this._serviceResponse);
this.renderHtml();
});
}
renderHtml() {
this.innerHTML = `
<table style="width: 100%;" border="2" >
<thead>
<th>Header1</th>
<th>Header2</th>
<th>Header3</th>
</thead>
<tbody>
${this._serviceResponse.map(employee => { return this.getEmployeeTemplate(employee); })}
</tbody>
</table>
`;
}
getEmployeeTemplate(employee: Employee) {
switch (employee.Type) {
case "1":
return this.getRegularTemplate(order);
case "2":
return `<tr><td colspan=3>Test Row}</td></tr>`;
}
}
getRegularTemplate(emp: Employee): string {
return `
<tr>
<td> ${emp.FirstName} </td>
<td> ${emp.LastName} </td>
<td>
${this.createLink(emp)}
</td>
</tr>
`;
}
createLink(emp: Employee): string {
var anchor = document.createElement('a');
anchor.innerHTML = 'Details';
anchor.onclick = () => { this.handleDetailsClick(emp); };
anchor.href = '#';
return anchor.outerHTML;
}
handleDetailsClick(emp: Employee) {
console.log('Details link clicked: ' + emp);
}
handleDetailsClick() {
console.log('clicked');
}
}
当它在 UI 上呈现时,我看到了这个锚标记,但缺少 onClick 事件处理程序。
<a href="#">Details</a>