【问题标题】:Jquery not firing dynamically created tableJquery没有触发动态创建的表
【发布时间】:2017-08-10 06:34:40
【问题描述】:

我目前正在开发一个 ASP.Net 应用程序,并且在那里动态构建了一个 HTML 表。

除标题行之外的每个表格行都可以重新排序。这主要是可行的,但是我编写的委托事件并不总是触发,因此用户可以在任何事情发生之前单击一段时间。

请查看我的代码并让我知道我哪里出了问题,因为这需要始终如一地工作并且适用于每个浏览器。

$('td').on('click', "a.up, a.down, a.top, a.bottom", function () {    

console.log("up or down arrow clicked");    

var row = $(this).parents("tr:first");    
var thisTable = row.closest("table");    
if ($(this).is(".up")) {    
    if (row[0].rowIndex > 1) {    
        row.insertBefore(row.prev());    
    }    
} else if ($(this).is(".down")) {    
    row.insertAfter(row.next());    
} else if ($(this).is(".top")) {    
    row.insertBefore($("table tr:first"));    
    row.insertAfter(row.next());    
} else {    
    row.insertAfter($("table tr:last"));    
}    

});  

非常感谢任何和所有帮助。

【问题讨论】:

    标签: javascript jquery asp.net delegates


    【解决方案1】:

    两件事:

    1. $('td').on('click', 更改为$('table').on('click',

    2. 您应该检查hasClass('.top'),而不是is('.top')

    以下是更新后的代码:

    $('table').on('click', "a.up, a.down, a.top, a.bottom", function() {
    
      console.log("up or down arrow clicked");
    
      var row = $(this).parents("tr:first");
      var thisTable = row.closest("table");
      if ($(this).hasClass(".up")) {
        if (row[0].rowIndex > 1) {
          row.insertBefore(row.prev());
        }
      } else if ($(this).hasClass(".down")) {
        row.insertAfter(row.next());
      } else if ($(this).hasClass(".top")) {
        row.insertBefore($("table tr:first"));
        row.insertAfter(row.next());
      } else {
        row.insertAfter($("table tr:last"));
      }
    
    });
    

    【讨论】:

    • 我没有看到我在使用is('.top'),但是我会尝试这个,但只是一个问题,为什么使用$('table') 而不是$('td')$(document)
    • $('table') 因为,您在其上触发事件的所有类都在表内。如果您使用document,则此事件将绑定到具有相同类但不在table 内的其他元素。你在这里使用is('.top')$(this).is(".top")
    • 哦,是的,我是。我正在寻找你的例子。
    【解决方案2】:

    代替:

    $('td').on('click', "a.up, a.down, a.top, a.bottom", function () {    
    

    试试

    $(document).on('click', "a.up, a.down, a.top, a.bottom", function () {
    

    【讨论】:

      【解决方案3】:

      修改代码:

      $('td').on('click', "a.up, a.down, a.top, a.bottom", function () { ....
      

      收件人:

      $(document).on('click', "a.up, a.down, a.top, a.bottom", function () { ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-08
        • 2010-10-28
        • 1970-01-01
        • 2011-12-03
        • 2011-04-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多