addEventListener註冊事件(通常搭配DOM)
const btn = document.querySelector(".btn");
const title = document.querySelector("h1");
btn.addEventListener("click", function(e) {
title.textContent = "按鈕已經被點擊";
})
練習---加法器
const btn = document.querySelector(".btn");
const title = document.querySelector("h1");
let count = 0;
btn.addEventListener("click", function(e) {
count += 1;
console.log("click");
title.textContent = count;
})
e.target 知道點到哪個DOM物件
const btn = document.querySelector(".btn");
btn.addEventListener("click", function(e) {
console.log(e.target);
})
e.target搭配nodeName
const btn = document.querySelector(".btn");
btn.addEventListener("click", function(e) {
console.log(e.target.nodeName);
console.log(e.target.innerHTML);
if (e.target.nodeName == "INPUT") {
console.log("你目前點到按鈕了!");
} //知道點到哪個DOM物件
})
preventDefault 取消預設行為
ex:原本應該連出外部,但是preventDefault則不會連出去
const myLink = document.querySelector("a");
myLink.addEventListener("click", function(e) {
e.preventDefault();
})