1. HTML event handler
In the earliest HTML event handler, we can directly pass in multiple parameters:
<div id="btn" onclick="clickBtn(event,2)">任务总数</div>
<script>
function clickBtn(event,val){
console.log(event);
console.log(val)
}
</script>
Note: event can be reversed but it must be the event keyword, not e. If it is e, an error will be reported: ReferenceError: e is not defined
That is, the correct approach in the case of HTML event handlers is to pass in the complete event name
Of course, you can also print correctly without passing any parameters (it can only be event)
<div id="btn" onclick="clickBtn()">任务总数</div>
<script>
function clickBtn(){
console.log(event);
}
</script>
Parameters can also be passed when event is not passed
<div id="btn" onclick="clickBtn(2)">任务总数</div>
<script>
function clickBtn(a){
console.log(event);
console.log(a)
}
2. "οnclick=function"以及addEventListener
<div id="btn">任务总数</div>
<script>
var btn=document.getElementById('btn')
btn.onclick = function(e){
console.log(e);
}
</script>
//addEventListener
<div id="btn">任务总数</div>
<script>
var btn=document.getElementById('btn')
btn.addEventListener('click',function(e){
console.log(e);
})
</script>
Note: The above two types can be passed in other identifiers such as e, but cannot be passed without parameters
But in these two event handlers, only event
parameters are passed in by default . If you want to pass in other parameters, you can encapsulate the method to handle it:
<div id="btn">任务总数</div>
<script>
var btn=document.getElementById('btn')
btn.onclick=function(e){
test(e,'aa')
}
function test(e,str){
console.log(e.target)
console.log(str)
}
</script>
//addEventListener
<div id="btn">任务总数</div>
<script>
var btn=document.getElementById('btn')
btn.addEventListener('click',function(e){
test(e,'aa')
})
function test(e,str){
console.log(e.target)
console.log(str)
}
</script>
to sum up:
1. In the earliest HTML event handler, we can directly pass in multiple parameters, and can directly pass in the event without passing in the event. It is very important to the event keyword, so it can be used directly.
2. The event keyword is no longer valued in "οnclick=function" and addEventListener, any logo can be passed, but only event