簡體   English   中英

我一直在向此按鈕添加事件偵聽器並收到錯誤消息。 我做錯了什么?

[英]I have been adding an event Listener to this button and getting an error. What I'm I doing wrong?

我一直在嘗試向此按鈕添加事件偵聽器並收到 Uncaught TypeError: Cannot read property 'addEventListener' of null

 let button = document.getElementById('submit'); function hello() { console.log("hello"); } button.addEventListener('click', hello);
 <div class="button"> <button id="submit">Submit</button> </div>

也許是因為 js 在 html 之前加載。 嘗試將您的 js 代碼放入此 function 中:

window.onload = () => {
    \\ your js code
}

代碼看起來很好,實際上正在工作!

但是,當您忘記或錯誤輸入元素的 id/class 時,通常會發生此問題。 所以當腳本嘗試監聽事件時,他無法找到元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM