【问题标题】:Add click event to datatable cell将点击事件添加到数据表单元格
【发布时间】:2020-02-17 01:32:13
【问题描述】:

我正在尝试将点击事件添加到动态创建的数据表中。所以这是我的 js:

   $('#report-table').dataTable({
        "proccessing": true,
        "serverSide": true,
        "ajax": {
            url: '@Url.Action("Get","Controller")',
            type: 'GET'

        },
       "columns": [
           { "data": "Name" },
                { "data": "Date" }, //lest say I want to add a click event here ???
                { "data": "sName", render: myRender }// I tried render but this is rendered without waiting on click function
        ]

    });

这是我的表,例如:

<tr role="row" class="odd">
<td class="sorting_1">A Test</td>
<td class="aaaa">2/13/2020 3:34:40 PM</td> //lets say I want to fire a click event when I click the .aaaa class
<td>
    <a  asp-route-fileid="55555555" asp-action="Download5"><img src="img/download.svg" height="30" width="30"></a>
</td>

假设我想在单击 .aaaa 类时触发一个单击事件。

谁能给我一个想法?我可以这样做吗? 我被困在这里。任何想法都会非常感激:)

【问题讨论】:

  • 这能回答你的问题吗? How to make datatable row or cell clickable?
  • 否,因为我想单击特定单元格,而不是所有行。具有特定类的特定单元格@Kurt
  • 您应该能够更改选择器。除了通用的tbody td,您还可以执行.yourClass 之类的操作。
  • 没有@Kurt。我已经试过了。所有的 td 都来自 db。如果我尝试你所说的,那当然是行不通的。
  • 您可以编辑您的问题以包含您尝试过的内容吗?这将防止回复只是建议您已经完成的工作。数据来自哪里并不重要,您仍然可以将事件附加到它。只需确保按照该链接中提到的方式附加它们,on('click', '.yourClass', function() {...})

标签: javascript jquery datatable datatables


【解决方案1】:

试试这个,更多请查看forum

$('#report-table').on('click', 'td.className', function (e) {
    // your code to do something
});

【讨论】:

    【解决方案2】:

    使用className 代替render 向单元格添加一个类

       "columns": [
            { "data": "Name" },
            { 
                "data": "Date",
                "className": "your-class"
            },
            { "data": "sName" }
       ]
    

    然后在你的类上放置一个点击事件处理程序

    $('#report-table').on('click', '.your-class', function() {
        //function code here
    }
    

    【讨论】:

      【解决方案3】:
      $("tr[role='row']").on('click',()=> {
          alert($(this).find('td.aaaa').text());
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-15
        • 1970-01-01
        • 2016-08-25
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        相关资源
        最近更新 更多