JavaScript闭包。访问循环到当前的i,j变量 [英] JavaScript closures. Access in loop to current i, j variables

查看:70
本文介绍了JavaScript闭包。访问循环到当前的i,j变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用jQuery动态生成< table> ,我想为每个单元格设置点击处理程序,因此当单击单元格时,弹出窗口将显示当前索引为细胞。如何在循环中访问CURRENT i j 变量?

I try to dynamically generate <table> with jQuery and I want to set click handlers to each cell, so when cell clicked the popup will appear with current index of cell. How I can access to CURRENT i and j variables in loop?

  for(var i = 0; i < 5; i++) {
      var tr = $('<tr></tr>');
      for (var j = 0; j < 5; j++) {
          var td = $('<td></td>');
          td.click(function() {
            alert(i + ' ' + j);  // here I want to access to CURRENT i, j variables
          })
          td.appendTo(tr);
      }
  }    


推荐答案

其他答案主要解释如何解决闭包问题,虽然这些方法不是特别节省内存,因为它们最终为 i 和<$ c的每个可能组合创建一个新的闭包。 $ c> j 。

The other answers mostly explain how to fix the closure problem, although such methods are not particularly memory efficient since they end up creating a new closure for each possible combination of i and j.

但是,由于您使用的是jQuery,因此您可以使用其他许多选项:

However, since you're using jQuery you have a number of other options available to you:

td.on('click', { i: i, j: j }, function(event) {
    var i = event.data.i;
    var j = event.data.j;
    alert(i + ' ' + j);
});

i event.data

$.each(Array(5), function(i) {
    // i is already bound here because it's a function parameter
    $.each(Array(5), function(j) {
        // and j available here
        td.on('click', ...);
    });
});



使用事件委托而不是每个元素处理程序



Use event delegation instead of a per-element handler

$('#myTable').on('click', 'td', function() {
    // use jQuery methods to determine the index, e.g.
    var j = this.cellIndex
    var i = this.parentNode.rowIndex
    ...
});

这比将单独的处理程序绑定到每个< td>更有效。 单独。

which is more efficient than binding a separate handler to each <td> individually.

您可以直接在元素上存储数据值,如果您想要检索单元格和行索引以外的值,这将非常有效:

You can store data values directly on elements, which would work very well if you wanted to retrieve values other than the cell and row indexes:

td = $('<td>').data({i: i, j: j});

然后直接从点击元素的 .data中提取这些行和列值

and then extract these row and column values directly from the clicked element's .data:

for (var i = 0; i < 5; i++) {
    var tr = $('<tr></tr>');
    for (var j = 0; j < 5; j++) {
        $('<td></td>').data({i: i, j: j}).appendTo(tr);
        td.appendTo(tr);
    }
}

$('#myTable').on('click', 'td', function() {
    var data = $(this).data();
    var i = data.i;
    var j = data.j;
    alert(i + ' ' + j);
});

这篇关于JavaScript闭包。访问循环到当前的i,j变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆