我正在尝试从 HTML 文件中的按钮运行 ts/js 文件。 我正在使用 TS 和 Node js。
这是我收到错误的一些代码
document.addEventListener('DOMContentLoaded', () => {
const saftbutton = document.getElementById('xbutton') as HTMLButtonElement;
xbutton.addEventListener('click', async () => {
try {
const startdateInput = document.getElementById('startdate') as HTMLInputElement;
const enddateInput = document.getElementById('enddate') as HTMLInputElement;
const startDate = startdateInput.value;
const endDate = enddateInput.value;
console.log('Start Date:', startDate);
console.log('End Date: ', endDate);
const response = await fetch('/prog/callback',
{
method: 'POST',
headers:
{
'Content-Type': 'application/json'
},
body: JSON.stringify({
startDate,
endDate
})
}
);
await start(2);
这是我得到的错误:
document.addEventListener('DOMContentLoaded', () => {
^
ReferenceError: document is not defined
有人可以帮我吗?
谢谢
您需要附加到
window
,因为在 document
被触发之前 DOMContentLoaded
可能尚未准备好:
window.addEventListener('DOMContentLoaded', () => {
// whatever you want
});