熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> JSP教程 >> 正文

jquery循環綁定事件

2022-06-13   來源: JSP教程 

  <html>

  <head>
        <title></title>
        <script type="text/javascript" src="
    </head>
    <body>
        <script type="text/javascript">
            $(document)ready(function () {
                var array = [ ];

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

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

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

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

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

  <input type="button" id="btn" value="btn" />
        <input type="button" id="btn" value="btn" />
        <input type="button" id="btn" value="btn" />
        <input type="button" id="btn" value="btn" />       
    </body>
</html>


From:http://tw.wingwit.com/Article/program/Java/JSP/201311/20058.html
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.