You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML与TypeScript关联按钮失效问题求助

解决TypeScript点击按钮生成表格无法复现的问题

浏览器无法直接运行TypeScript代码,必须先编译为JavaScript才能执行。你的代码逻辑本身没问题,问题出在HTML直接引入.ts文件的方式上,按以下步骤就能解决:

1. 编译TypeScript为JavaScript

  • 先确认已安装TypeScript,没装的话在终端执行:npm install -g typescript
  • 进入代码所在目录,运行编译命令:tsc script.ts,执行后会生成对应的script.js文件

2. 修改HTML的脚本引入路径

把原HTML里的<script src="script.ts"></script>替换成:

<script src="script.js"></script>

3. 可选:自动监听编译(提升开发效率)

如果需要频繁修改代码,可执行tsc script.ts --watch,TypeScript会自动监听.ts文件的变化,实时重新编译为.js


修改后的完整HTML代码

<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <title>Title</title>
     <script src="script.js"></script>
</head>
<body>
    <input type="button" value="Generate a table" onclick="generateTable()" />
</body>
</html>

你的TypeScript代码无需修改

function generateTable() {
    // creates a <table> element and a <tbody> element
    const tbl = document.createElement("table");
    const tblBody = document.createElement("tbody");

    // creating all cells
    for (let i = 0; i < 2; i++) {
        // creates a table row
        const row = document.createElement("tr");

        for (let j = 0; j < 2; j++) {
            // Create a <td> element and a text node, make the text
            // node the contents of the <td>, and put the <td> at
            // the end of the table row
            const cell = document.createElement("td");
            const cellText = document.createTextNode(`cell in row ${i}, column ${j}`);
            cell.appendChild(cellText);
            row.appendChild(cell);
        }

        // add the row to the end of the table body
        tblBody.appendChild(row);
    }

    // put the <tbody> in the <table>
    tbl.appendChild(tblBody);
    // appends <table> into <body>
    document.body.appendChild(tbl);
    // sets the border attribute of tbl to '2'
    tbl.setAttribute("border", "2");
}

内容的提问来源于stack exchange,提问作者Fabian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 16:50:26