在使用for循环分配数据时,在表td上单击侦听器

问题描述 投票:1回答:2

我正在尝试为我的任务的一部分创建一个表,我很难以正确的方式实现事件监听器。似乎我试图显示<td>here</td>is的数据已修复,我不知道如何解决这个问题。

对表行的事件侦听器有一些很大帮助但是我找不到使用循环来分配数据的示例。

这是我的代码:

var functionCreate = function(intWidth, intHeight) {
    var myRow;
    var intCell;

    $('#output').append('<table border = \"1\">');

    for(var i = 0; i< intHeight;i++){

        $('#output').find('table').append('<tr>');
        for(var j = 0; j < intWidth; j ++){
            intCell = 'click me';

            $('#output').find('tr:last').append('<td>'+intCell)

            $('#output').on('click',"td", function(){

                $(this).text((i+1).toString()+'.'+(j+1).toString());//(row.col)
            })
        }
    }

        return jQuery('output');
};

会发生什么是最终的row.col值在这里分配给所有<td></td>。我不知道如何给每个人一个不同的价值。

所以,如果我通过functionCreate(3,5)。行中的所有数据(点击后)变为5.3

我想我的问题是如何仅将点击行为分配给相关的<td></td>?或者有没有其他方法来传递数据?

谢谢你。

javascript jquery
2个回答
2
投票

这个问题是因为hoisting

最小的错误再现

// Demonstration of how easy it is for this to mess up your loops.
    
    var txt = ["a","b","c"];
    
    for (var i = 0; i < 3; ++i ) { 
       var msg = txt[i];
        setTimeout(function() { alert(msg); }, i*1000);        
    }
    
    // Alerts 'c', 'c', 'c'

// Pattern to avoid that by binding to variable in another function.

var txt = ["a","b","c"];

for (var i = 0; i < 3; ++i ) {    
    setTimeout((function(msg) { 
      return function() { alert(msg); } 
    })(txt[i]), i*1000);        
}

// Alerts 'a','b','c'

-1
投票

您可以使用数据属性来避免提升问题。

var functionCreate = function(intWidth, intHeight) {
    var myRow;
    var intCell;

    $('#output').append('<table border = \"1\">');

    for(var i = 0; i< intHeight;i++){

        $('#output').find('table').append('<tr>');
        for(var j = 0; j < intWidth; j ++){
            intCell = 'click me';

            var cell = $('<td>'+intCell).data('row', i+1).data('col', j+1);
            $('#output').find('tr:last').append(cell);
        }
    }

        return jQuery('output');
};



$('#output').on('click',"td", function(){
    var $this = $(this);
    var row = $this.data('row');
    var col = $this.data('col');

    $this.text(row+'.'+col);//(row.col)
})

并且,事件注册可以从循环移动到外部。

© www.soinside.com 2019 - 2024. All rights reserved.