Home > Article > Web Front-end > About js index subscript li collection binding click event example sharing
This article uses a piece of example code to explain to you the relevant knowledge of binding click events to the li collection of js index subscripts. The code is simple and easy to understand, very good, and has reference value. Friends who need it can refer to it. I hope it can help. to everyone.
The following code introduces you to the li collection binding click event. The specific code is as follows:
//Method-1: var items = document.getElementsByTagName('li'); for(var i=0;i<items.length;i++){ items[i].index = i; items[i].onclick = function(){ this.innerHTML = this.index; } } //Method-2: var items = document.getElementsByTagName('li'); for(var i = 0; i<items.length; i++){ (function(index){ items[i].onclick = function(){ this.innerHTML = index; } })(i) } //Method-3: var items = document.getElementsByTagName('li'); for(var i = 0; i<items.length; i++){ items[i].onclick = function(index){ return function(){ this.innerHTML = index; } }(i) }
Related recommendations:
jQuery simple binding single event example sharing
Example explanation jQuery realizes html two-way binding function
Examples to explain the usage of JavaScript function binding
The above is the detailed content of About js index subscript li collection binding click event example sharing. For more information, please follow other related articles on the PHP Chinese website!