这个问题绝对是经典,然后值得仔细分析,要能够明白为什么要这样做
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
</style>
</head>
<body>
<button id="button-1">one</button>
<button id="button-2">two</button>
<button id="button-3">three</button>
<button id="button-4">four</button>
<a href="#">点击</a>
<script>
var getbtn = document.getElementsByTagName('button');
//alert(getbtn);
/*
*************方法1************
for(var i = 0;i < getbtn.length;i++){
getbtn[i].onclick = function(index){
console.log(getbtn[index].innerHTML);
}.bind(null,i);
}
*************方法2************
for(var i = 0;i < getbtn.length;i++){
getbtn[i].onclick = function(){
console.log(this.innerHTML);
}
}
*************方法3*************
for(let i = 0;i < getbtn.length;i++){
getbtn[i].onclick = function(){
console.log(getbtn[i].innerHTML);
}
}
*************方法4**************
for(var i = 0;i < getbtn.length;i++){
getbtn[i].onclick = (function(index){
var that = getbtn[index];
return function(){
console.log(that.innerHTML);
}
})(i);
}
***************方法5****************
document.body.addEventListener("click",function(e){
if(e.target && e.target.nodeName == "BUTTON"){
var item = e.target;
console.log(item.innerHTML);
}
},false);
*/
</script>
</body>
</html>