【问题标题】:.on click event not always working on dynamically added table rows.on 点击​​事件并不总是适用于动态添加的表格行
【发布时间】:2018-10-17 07:37:06
【问题描述】:

我有一个动态添加表行的表和一个 jquery 代码,用于在具有特定类的行上添加 .on click 事件。关键是代码运行良好,但只是有时......当我将鼠标悬停在表格行上时,80% 的调试会话鼠标开始闪烁,并且该事件在该行上单击 20 次后工作。

表:

<div id="main-tbl">
    <table id="tbl" class="table">
    </table>
</div>

jQuery

$("#tbl").on("click", "tr", function () {
    alert("test");
});

通过 ajax 添加行

$.ajax({
    url: 'index.aspx/GetData',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    type: "POST",
    success: function (data) {
        debugger;
        if (data.d.length > 0) {
            var newdata = data.d;
            $tbl.empty();
            $tbl.append('<tr><th>Test</th></tr>');
            var rows = [];
            for (var i = 0; i < newdata.length; i++) {
                rows.push('<tr><td>newdata[i].Test</td></tr>');
            }
            $tbl.append(rows.join(''));
        }
    }
});

基础是asp.net,使用signalr+ajax从sqldb加载数据。

有没有人知道为什么它有时只工作?

-亚历山大

【问题讨论】:

  • 学习Event Delegation使用$("#tbl").on("click", "tr", function () { alert("test"); });
  • 我也用过,输出是一样的。

标签: javascript jquery asp.net


【解决方案1】:

当您处理动态创建的行时,代码应该是这样的。

$(document).on("click", "tr", function () {
  alert("test");
});

【讨论】:

    【解决方案2】:

    基于 Satpals 的回答:

    $("#tbl").on("click", "tr", function() {
      $("#tbl").append('<tr><td>Test</td></tr>');
      console.log($(this).index());
      //alert("test");
    });
    <div id="main-tbl">
      <table id="tbl" class="table">
        <tr>
          <td>New!</td>
        </tr>
      </table>
    </div>

    【讨论】:

    • 我知道代码及其工作原理,但关键是该表没有响应 80% 的调试会话
    猜你喜欢
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多