【问题标题】:JavaScript - jquery DataTable append button to row + click eventJavaScript - jquery DataTable 将按钮附加到行+单击事件
【发布时间】:2025-12-14 16:05:02
【问题描述】:

是否可以在数据表构建行时附加点击事件?无需调用外部全局函数并找到关闭 tr 并获取 DATA 对象。

$('#example').DataTable({
     columns : [{
        title   : 'msg',
        sClass  : 'col-sm-2',
        render  : function(data, type, row){
            var b = $('<button>the button</button>').click(function(){
                alert(row.msg);
            })
            return b;
        }
     }],
     ajax:{
        type : 'POST',
        url  : 'foo.php',
     }
});

我知道上面的例子dosnt工作,cos渲染函数必须返回字符串,它只是我需要的一个例子。

  • 创建一个元素。
  • 附加单击函数传递“行”对象,而不调用全局函数。

【问题讨论】:

    标签: jquery datatables


    【解决方案1】:

    简短的回答,不,你不能。我知道您不想想要,但我会使用类和事件委托,如下所示:

    var myDataTable=$('#example').DataTable({  // note the stored reference to the dataTable
         columns : [{
            title   : 'msg',
            sClass  : 'col-sm-2',
            render  : function(data, type, row){ 
                return '<button class="some-class">the button</button>';
            }
         }],
         ajax:{
            type : 'POST',
            url  : 'foo.php',
         }
    });
    
    
    $(document).on('click', '.some-class', function(){ 
            var $btn=$(this);
            var $tr=$btn.closest('tr');
            var dataTableRow=myDataTable.row($tr[0]); // get the DT row so we can use the API on it
            var rowData=dataTableRow.data();
            console.log(rowData.msg);
    });
    

    技术上你可以在每行渲染后使用rowCallback function附加处理程序,但你必须使用.find()或类似的方法才能返回按钮和概述的方法以上是更清洁恕我直言。

    【讨论】:

      【解决方案2】:

      你可以使用“columns.createdCell”来得到你想要的:

      $( '#example' ).DataTable( {
          columns         : [ {
              data        : 'msg',
              title       : 'msg',
              sClass      : 'col-sm-2',
              createdCell : function( td, cellData, rowData, row, col ){
                  var b = $( '<button>the button</button>' ).click( function() {
                      alert( rowData.msg );
                  } );
                  $( td ).html( b );
              }
          } ],
          // using data instead of ajax to demonstrate
          data            : [
              { msg       : 'Message 1!' },
              { msg       : 'Message 2!' },
              { msg       : 'Message 3!' }
          ],
          /*
          ajax            : {
              type        : 'POST',
              url         : 'foo.php',
          }
          */
      } );
      

      只需将b 传递给$( td ).html(),瞧!

      【讨论】:

        【解决方案3】:

        同时添加模糊和焦点允许点击并继续输入

        if (dataTable.columns(colunIndex).search() !== e.value) {
            dataTable.columns(colunIndex)
                .search(e.value)
                .draw();
            $(this).blur();
            $(this).focus();
        }
        

        【讨论】: