Use closures to implement onclick event passing parameters

When the click event is triggered, a simple example.

<!DOCTYPE html>
<html>
<head>
    <title>闭包创建数组</title>
    <meta charset="utf-8">
    <script type="text/javascript">
        window.onload = function (){
     
     
            var lis = document.getElementsByTagName('li');

            for (var i = 0; i < lis.length; i++) {
     
     
                lis[i].onclick = function () {
     
     
                    console.log(this.innerHTML);
                };
            }
        }
    </script>
</head>
<body>
    <h2>闭包点击事件</h2>
    <ul>
        <li>奔驰</li>
        <li>宝马</li>
        <li>奥迪</li>
    </ul>
</body>
</html>

But when I want to get the variable value outside the loop.

<!DOCTYPE html>
<html>
<head>
    <title>闭包创建数组</title>
    <meta charset="utf-8">
    <script type="text/javascript">
        window.onload = function (){
     
     
            var lis = document.getElementsByTagName('li');
            var price = [1, 10, 100];

            for (var i = 0; i < lis.length; i++) {
     
     
                lis[i].onclick = function () {
     
     
                    console.log(this.innerHTML+ '的价格:' + price[i]);
                };
            }
        }
    </script>
</head>
<body>
    <h2>闭包点击事件</h2>
    <ul>
        <li>奔驰</li>
        <li>宝马</li>
        <li>奥迪</li>
    </ul>
</body>
</html>

Insert picture description here
Since when I click, the value of i is already 3, so it will be undefined. The question now is how to save the value of i in each loop.

<!DOCTYPE html>
<html>
<head>
    <title>闭包创建数组</title>
    <meta charset="utf-8">
    <script type="text/javascript">
        window.onload = function (){
     
     
            var lis = document.getElementsByTagName('li');
            var price = [1, 10, 100];

            for (var i = 0; i < lis.length; i++) {
     
     
                lis[i].onclick = (function (n) {
     
     
                    console.log("i:"+i+";n:"+n);
                    return function () {
     
     
                        console.log(this.innerHTML+ '的价格:' + price[n]);
                    };
                })(i);
            }
        }
    </script>
</head>
<body>
    <h2>闭包点击事件</h2>
    <ul>
        <li>奔驰</li>
        <li>宝马</li>
        <li>奥迪</li>
    </ul>
</body>
</html>

The classic answer to closures should be: Extend the life cycle of local variables
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43248623/article/details/114985683