DOM0事件绑定
<button>点击</button>const btn = document.querySelector('button')btn.onclick = function(){const bgColor = '#000000';document.body.style.backgroundColor = bgColor;}//下面写法同义function bgChange(){const bgColor = '#000000';document.body.style.backgroundColor = bgColor;}btn.onclick = bgChange
DOM2事件绑定
addEventListener
btn.addEventListener(eventType, function () {}, false);
三个参数:事件名(click),处理程序,布尔值(true为事件捕获阶段调用处理程序,false为事件冒泡阶段处理程序)
<button>点击</button>const btn = document.querySelector('button')function bgChange(){const bgColor = '#000';doucument.body.style.backgroundColor = bgColor;}btn.addEventListener('click',bgChange)//下面写法同义btn.addEventListener('click', function(){const bgColor = '#000';doucument.body.style.backgroundColor = bgColor;})
removeEventListener
btn.removeEventListener('click',bgChange)
添加多个事件时,要采用DOM2事件绑定
btn.onclick = functionAbtn.onclick = functionBfunctionB会覆盖functionAbtn.addEventListener('click',functionA)btn.addEventListener('click',functionB)此时fanctionB和FunctionA都是生效的
切记:上述两种方法都不可以,在方法名后加(),类似这种 btn.onclick = functionA() ❌,错误的写法,函数在渲染的时候直接执行掉了,点击的时候不再生效了。所以也就无法用这种方式传参数。
以下方法可以参考作为参数传递
行内事件处理
<button onclick="bgChange()">点击</button>function bgChange(){const bgColor = '#000000';doucumnet.body.style.backgroundColor = bgColor;}//这种也支持<button onclick = "alert('hello')">点击<button>
不建议使用:
- html和js不要混在一起
 - 多个btn添加事件时,增加工作量
//这种是支持的const btns = document.querySelectorAll('button');for(let i = 0; i< btns.length; i++){btns[i].onclick = bgChange}
 
