Event listener in JavaScript
绑定事件
所谓的“事件监听器”,指的是使用
addEventListener()
方法为一个元素添加事件,我们又称之为“绑定事件”。
obj.addEventListener(type, fn, false)
- type: 事件类型
- fn: 匿名函数
- false: 表示事件冒泡阶段调用
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script>
window.onload = function () {
var oBtn = document.getElementById("btn");
oBtn.addEventListener("click", alertMe, false);
function alertMe() {
alert("this is EventListener click 1");
};
oBtn.addEventListener("click", function () {
alert("this is EventListener click 2")
}, false);
}
</script>
</head>
<body>
<input id="btn" type="button" value="按钮"/>
</body>
</html>
以下两种表示均可
obj.addEventListener("click", function () {...}, false);
obj.onclick = function () {...};
解绑事件
obj.removeEventListener(type, fn, false);
jquery 用法举例
$(function () {
$('#clickButton').click(function () {
fetch("/getReq").then((res)=>{
return res.json();
})
.then((json)=>{
console.log(json.data)
})
})
})
Disclaimer
- License under
CC BY-NC 4.0
- Copyright issue feedback
me#imzye.me
, replace # with @ - Not all the commands and scripts are tested in production environment, use at your own risk
- No privacy information is collected here