[英]Onclick function not called when its inside a load event listener
我想確保我的JavaScript僅在加載所有內容之后才能工作。 因此,我將代碼放入了加載事件監聽器中。 如果我在該事件內創建一個函數,然后嘗試在onclick事件中的某個按鈕中調用它,則會收到一條錯誤消息,提示未定義我的函數。
錯誤:未捕獲ReferenceError:在HTMLButtonElement.onclick中未定義sayHello
如果我從加載事件中刪除該函數,它將起作用。 為什么會這樣?
的index.html
<html>
<head>
<script src="/js/index.js"></script>
</head>
<body>
<button onclick="sayHello()">Say Hello</button>
</body>
</html>
index.js
window.addEventListener("load", async () => {
function sayHello(){
alert("Hello!");
}
});
這樣嘗試。 在此模型中,在觸發DOMContentLoaded
事件之前,我們不會分配click
函數。
document.addEventListener('DOMContentLoaded', () => { document.querySelector('.sayHello').addEventListener('click', () => console.log('Hi')) });
<html> <head> <script src="/js/index.js"></script> </head> <body> <button class="sayHello">Say Hello</button> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.