DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> JavaScript綜合知識 >> jquery循環綁定事件
jquery循環綁定事件
編輯:JavaScript綜合知識     

 <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>

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved