0

可能重复:
如何在 Jquery 中选中复选框时收听

我正在使用 JQuery 动态创建许多复选框,如下所示。

     function createCheckbox(len){

        for(var i = 0; i < len; i++){
            $('#checkboxes').append('<input type="checkbox" ' + 'id=' + i + '></input>');
        }
        return;
      }

在 HTML 中,我有:

<div id="checkboxes"></div>

我的目标是每当检查复选框时,能够将其ID(或值)发送到此功能:

function hideColumn(columnIndex){
        $('#chart2 td:nth-child(' + (columnIndex+1) + ')').hide(); 
        return;
      }

这将能够处理在我的表中隐藏特定列的逻辑。有人可以帮我吗?谢谢

4

4 回答 4

1

当您checkbox动态创建时,您必须使用 jQuery 使用委托事件.on()

$('#checkboxes').on('change', ':checkbox', function() {
  if( this.checked ) {
    hideColumn( this.id ); // to send value use:   this.value
                           // but in your append code 
                           // there is no value attribute
  }
});

笔记

.on()委托事件的语法如下:

$( StaticElement ).on( eventName, target, handlerFunction );

其中,StaticElement指的是非动态元素。

于 2012-07-18T14:52:43.990 回答
1

可能你可以试试这个,只需修改 createCheckbox 函数:

function createCheckbox(len){
    for(var i = 0; i < len; i++){
        $('<input type="checkbox" ' + 'id=' + i + '></input>').on('change', function(e) {
            if (this.checked) {
                hideColumn(this.id);
            }
        }).appendTo($('#checkboxes'));
    }
    return;
}
于 2012-07-18T15:01:32.000 回答
0

在 jQuery API 中看起来很简单!

function createCheckbox(len) {    
  for (var i = 0; i < len; i++) {        
    $('<input type="checkbox" ' + 'id=' + i + '></input>').on('change', function(e) {
      if (this.checked) {
        hideColumn(this.id);
      }
    }).appendTo($('#checkboxes'));
  }
  return; 
} 
于 2012-07-18T15:09:09.530 回答
0

你有没有尝试过这样的事情?:

$("#checkboxes :checkbox").on('change', function(e) {
    if (this.checked) {
        hideColumn(this.id);
    }
});
于 2012-07-18T14:56:25.477 回答