我没有 javascript 和 typescript 的经验。当我使用 PHP 时,我将导航栏制作成一个可以回显 html 代码的函数。这也可以使用打字稿来实现吗?我创建了一个返回 html 代码字符串的函数,但当我在 html 页面上调用该函数时(如果打字稿代码正确的话),我不知道如何实际使其渲染 html。
export function navbar(): string {
const menuItems: MenuItems = {
Home: "index.html",
About: "about.html",
FAQ: "faq.html",
Contact: "contact.html",
};
let htmlCode: string = "<nav><ul>";
for (const [key, value] of Object.entries(menuItems)) {
htmlCode += `<li><a src="${key}">${value}</a></li>`;
}
htmlCode += "</nav></ul>";
return htmlCode;
}
只需将其放入
<script></script>
标签即可!
<body>
<!--some html tags -->
<script>
export function navbar(): string {
const menuItems: MenuItems = {
Home: "index.html",
About: "about.html",
FAQ: "faq.html",
Contact: "contact.html",
};
let htmlCode: string = "<nav><ul>";
for (const [key, value] of Object.entries(menuItems)) {
htmlCode += `<li><a src="${key}">${value}</a></li>`;
}
htmlCode += "</nav></ul>";
return htmlCode;
}
</script>
</body>