3.12 DOM 基礎事件綁定

click 事件

例:

html:

<button type="button" id="my_btn">按鈕</button>

透過 js ,替按鈕綁定 click 事件:

let the_btn = document.getElementById("my_btn");
the_btn.addEventListener("click", function(){
  alert("文字訊息");
});

認識 disabled 屬性

在 button 標籤上,加 disabled 屬性,例:

<button type="button" id="my_btn" disabled>按鈕</button>

除了外觀上的改變之外,會發現:click 事件上的綁定就會失效

認識 this 關鍵字

在 JS 當中的匿名函式,將 this 印出來看,例:

this:看似簡單,但其實複雜,掌握一個原則:根據程式的上下文,this 會自動綁定到不同的物件,若不確定它是什麼,就將 this 印至 console 中來看。 以目前的情況來看,this 就是 the_btn 變數裡的東西

使用 JS 來操控 disabled 屬性

在匿名函式當中,加以下的程式:

作用:按鈕加上 disabled 屬性,以致於按鈕第二次點擊時,就不會再觸發 click 事件。

Last updated