jquery迴圈綁定事件

來源:互聯網
上載者:User

 <html>

    <head>
        <title></title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    </head>
    <body>
        <script type="text/javascript">
            $(document).ready(function () {
                var array = [0, 1, 2, 3];

                // 1.
                /*
                for(var index in array) {
                    $("#btn" + index).click(function() {
                        var item  = array[index];
                        alert(item);
                    });
                }*/
                // 始終彈出3, 因為function() {} 並沒有被立即解析,直到調用的時候才被解析,這時index已經是3了。


                // 2.
                /*
                for(var index in array) {
                    $("#btn" + index).click(function(i) {
                        var item  = array[i];
                        alert(item);
                    }(index));
                }*/
                // 立即彈出0, 1, 2, 3,因為使用了function() {}(index)立即被解析,遇到alert,就立即彈出來了。


                // 3.
                /*for (var index in array) {
                    $("#btn" + index).click(function (i) {
                        return function () {
                            var item = array[i];
                            alert(item);
                        };
                    } (index));
                }*/
                // 正確執行,點擊btn0,彈出0,點擊btn1,彈出1...
                // 1.因為function(i) {}(index)是被立即解析的,所以i依次送入的是0, 1, 2, 3
                // 2.內部沒有直接alert,是因為不想立即執行,想點擊時再執行,所以返回了一個函數出去。


                // 4.
                for (var index in array) {
                    $("#btn" + index).bind("click", {index: index}, clickHandler);
                }

                function clickHandler(event) {
                    var index = event.data.index;
                    var item = array[index];
                    alert(item);
                }
                // 正確執行,點擊btn0,彈出0,點擊btn1,彈出1...
                // 利用了event.data,因為index在綁定的時候已經被持久化到event.data中了,所以響應的時候我們可以取到。
            });
       
        </script>

        <input type="button" id="btn0" value="btn0" />
        <input type="button" id="btn1" value="btn1" />
        <input type="button" id="btn2" value="btn2" />
        <input type="button" id="btn3" value="btn3" />       
    </body>
</html>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.