代码拉取完成,页面将自动刷新
同步操作将从 技术蛋老师/TypeScript教程 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
const url: string = 'https://api.thecatapi.com/v1/images/search';
const button: HTMLButtonElement | null = document.querySelector('button');
const tableBody: HTMLTableElement | null = document.querySelector('#table-body');
interface CatType {
id: string;
url: string;
height: number;
width: number;
test?: boolean;
}
class Cat implements CatType {
id: string;
url: string;
height: number;
width: number;
constructor(id: string, url: string, height: number, width: number) {
this.id = id;
this.url = url;
this.height = height;
this.width = width;
}
}
class WebDisplay {
public static addData(data: CatType): void {
const cat: Cat = new Cat(data.id, data.url, data.height, data.width);
const tableRow: HTMLTableRowElement = document.createElement('tr');
tableRow.innerHTML = `
<td>${cat.id}</td>
<td><img src="${cat.url}" /></td>
<td>${cat.height.toString()}</td>
<td>${cat.width.toString()}</td>
<td>${cat.url}</td>
<td><a href="#">X</a></td>
`;
tableBody?.appendChild(tableRow);
}
public static deleteData(deleteButton: HTMLAnchorElement): void {
const td = deleteButton.parentElement as HTMLTableCellElement;
const tr = td.parentElement as HTMLTableRowElement;
tr.remove();
}
}
async function getJSON<T>(url: string): Promise<T> {
const response: Response = await fetch(url);
const json: Promise<T> = await response.json();
return json;
}
async function getData(): Promise<void> {
try {
const json: CatType[] = await getJSON<CatType[]>(url);
const data: CatType = json[0];
WebDisplay.addData(data);
}
catch (error: Error | unknown) {
let message: string;
if (error instanceof Error) {
message = error.message;
} else {
message = String(error);
}
console.log(error);
}
}
button?.addEventListener<'click'>('click', getData);
tableBody?.addEventListener<'click'>('click', (ev: MouseEvent) => {
WebDisplay.deleteData(<HTMLAnchorElement>ev.target);
});
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。