自递归调用(可能由于关闭涉及)

时间:2014-03-28 02:48:15

标签: javascript jquery

我基本上有这段代码:

$(document).ready(function() {
  (function fillOutTable() {
    $.ajax({
      type: 'GET',
      url: 'someUrl',
      success: function(data) {
        var myTable = $("#tbl1");
        for(var i in data.myCollection) {
          /*filling out the table*/
          var str = $(
            ["<tr>",
            "<td>", counter++, "</td>",
            "<td>",
                "<a href='#' class='myClass'>", data.myCollection[i].object1.name, "</a>",
            "</td>",
            "<td>", title1,  "</td>",
            "<td>", title2,  "</td>",
            "<td>", title3,  "</td>"
            "</tr>"].join("")
          );

          myTable.find("tbody").append(str);
          myTable.find("tbody").on("click", ".myClass", function() {
            $('#twitterBtstrModal').on('shown.bs.modal', function() {
              alert('yes: ' + data.myCollection[i].object1.name);
            }).modal();
          });
        }
      },

      error: function(jqXHR, textStatus, errorThrown) {
        showNoDataMessage();
        alert('Something went wrong!');
      }
    });
})();

此代码存在两个问题:

  1. 当我点击表格中的链接(这是data.myCollection[i].object1.name的文字)时,无论我点击什么链接,它都会在警报中向我显示相同的数据yes: data.myCollection[i].object1.name 。虽然html代码在所有这些代码中都有所不同。

  2. 我点击链接的次数越多,每次点击的提醒就越多:第一次出现只有一个提醒,下次有2个,下次有4个或者什么。

1 个答案:

答案 0 :(得分:1)

有多个问题

  • 在循环中使用闭包变量
  • 绑定事件处理程序在另一个...等等

尝试

jQuery(function ($) {
    var myTable = $("#tbl1"),
        $tbody = myTable.find("tbody"),
        $model = $('#twitterBtstrModal');

    $.ajax({
        type: 'GET',
        url: 'someUrl',
        success: function (data) {

            $.each(data.myCollection, function (i, data) {
                /*filling out the table*/
                var str = $(
                ["<tr>",
                    "<td>", counter++, "</td>",
                    "<td>",
                    "<a href='#' class='myClass'>", data.myCollection[i].object1.name, "</a>",
                    "</td>",
                    "<td>", title1, "</td>",
                    "<td>", title2, "</td>",
                    "<td>", title3, "</td>"
                "</tr>"].join(""));

                //store the row data using data api
                $(str).appendTo($tbody).data('rowdata', data)
            });
        },

        error: function (jqXHR, textStatus, errorThrown) {
            showNoDataMessage();
            alert('Something went wrong!');
        }
    });

    //register these events only once

    //a delegated handler which will get the current rows data and set it to the modal
    $tbody.on("click", ".apiKeyName", function () {
        $model.data('mydata', $(this).closest('tr').data('rowdata')).modal();
    });
    $model.on('shown.bs.modal', function () {
        //read the data from the modal's data 
        var data = $model.data('mydata');
        alert('yes: ' + data.object1.name);
    })
});

免责声明:未经测试