In the typical js issue, click li to bring up the current li index and innerHTML functions.
In the typical js issue, click li to bring up the current li index and innerHTML functions.
If you click one of them, alert is required to output the following results:
According to our general idea, the code should be written as follows:
var myul = document.getElementsByTagName("ul")[0];var list = myul.getElementsByTagName("li");function foo(){for(var i = 0, len = list.length; i < len; i++){list[i].onclick = function(){alert(i + "----" + this.innerHTML);}}}foo();
Unfortunately, the result is as follows:
Why is index always 4? This is caused by no block-level scope in js. There are three solutions
1. Use closures
<script type="text/javascript">var myul = document.getElementsByTagName("ul")[0];var list = myul.getElementsByTagName("li");function foo(){for(var i = 0, len = list.length; i < len; i++){var that = list[i];list[i].onclick = (function(k){var info = that.innerHTML;return function(){alert(k + "----" + info);};})(i);}}foo();</script>
2. Use the new feature let in ES6 to declare Variables
Variables declared with let will have block-level scopes, which can obviously meet the requirements. However, it should be noted that a 'use strict '(using the strict mode) will take effect.
<script type="text/javascript">var myul = document.getElementsByTagName("ul")[0];var list = myul.getElementsByTagName("li");function foo(){'use strict'for(let i = 0, len = list.length; i < len; i++){list[i].onclick = function(){alert(i + "----" + this.innerHTML);}}}foo();</script>
3. Introduce jquery and use on or delegate to bind events (they all have the feature of event proxy)
<Script type = "text/javascript" src = "jquery-1.8.2.min.js"> </script>
<script type="text/javascript">$("ul").delegate("li", "click", function(){var index = $(this).index(); var info = $(this).html();alert(index + "----" + info);});</script><script type="text/javascript">$("ul").on("click", "li", function(){var index = $(this).index(); var info = $(this).html();alert(index + "----" + info);});</script>