Event listener in JavaScript
Binding Events
The so-called “event listener” refers to adding an event to an element using the addEventListener () method, which we also call “binding events.”
obj.addEventListener(type, fn, false)
- type: event type
- fn: anonymous function
- false: indicates calling during the event bubbling phase
<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>
Both of the following expressions are acceptable:
obj.addEventListener("click", function () {...}, false);
obj.onclick = function () {...};
Removing Events
obj.removeEventListener(type, fn, false);
Example of using jquery
$(function () {
$('#clickButton').click(function () {
fetch("/getReq").then((res)=>{
return res.json();
})
.then((json)=>{
console.log(json.data)
})
})
})
Back to Table of Contents
Disclaimer
- License under
CC BY-NC 4.0
- Copyright issue feedback
me#imzye.com
, replace # with @ - Not all the commands and scripts are tested in production environment, use at your own risk
- No personal information is collected.
Feedback