JavaScript-How to bind events and functions?
event
What is an event?
Some actions when the user operates on the page, such as left-click, double-click, stroke in, stroke out, etc.
Characteristics of event functions
All lowercase and starting with on ! ! !
For example: click at the beginning of the onclick on event is the event name click
The relationship between functions and events
When the event is triggered, the function is called through the user's action (click, double-click, slide in, slide out, etc.).
How to bind events and functions?
There are two ways to bind events and functions: one is to bind directly through HTML; the other is to convert HTML elements into JS objects and bind through JS objects
Direct binding via HTML
- onclick is an event that represents the action performed by a click event
- Bind the stand-alone event of the button element to the fun function
- event type="function name()
<button onclick="fun()">点击</button>
JS
<script>
var fun = function(){
console.log("通过HTML直接绑定!");
}
</script>
Binding via JS object
- HTML
<button id="btn">点击</button>
- Need to convert HTML elements to JS objects
//document.getElementById("ID名"):将ID对象的HTML元素转为JS对象
var oBtn = document.getElementById("btn");
- How to operate HTML elements through js objects
: js object.property name
var fun = function(){
console.log("通过js对象的操作HTML元素");
}
oBtn.onclick = fun;
Another way to write
oBtn.onclick = function(){
console.log("通过js对象的操作HTML元素2");
}