【问题标题】:Table rows does not shows up in Page Source表格行未显示在页面源中
【发布时间】:2014-04-11 19:12:28
【问题描述】:

我正在通过 Ajax 响应在我的 jquery 中填充一个表。我需要单击表格的行来填充更多信息。当我单击该行以提取row_id 时,使用以下代码:

(function(){
    $('#bags_table tr').click(function() {
            alert(1)
          alert($(this).attr('id')); //trying to alert id of the clicked row          

    });
});

单击该行时,不会发生警报。在查看页面源时,它显示一个空表。

我正在生成这样的表格。

function bags_table_func(result){

    var rows = "<tr><th>Seal No.</th><th>Status</th><th>Destination</th><th>Total Packets</th><th>Max. Weight</th>" + 
               "<th>Min. Weight</th><th>Avg. Weight</th><th>Total Weight</th></tr>"

    for (var obj in result){
        if (obj == 'last_bagged_on'){
                continue
        }
        else if (result[obj]['status'] == undefined){
            rows += "<tr><td>No Content</td></tr>"
            break
        }
        rows += "<tr id = '"+obj+"'><td>" + obj+"</td><td>" + result[obj]["status"] + "</td><td>" + 
                    result[obj]["destination"] + "</td><td>" + result[obj]["total_packets"] + "</td><td>" + 
                    result[obj]["max_weight"] + "</td><td>" + result[obj]["min_weight"] + "</td><td>" + 
                    result[obj]["avg_weight"] + "</td><td>" + result[obj]["total_weight"] + "</td><td><a href = '#'>Details</td></tr>"
    }
    $("#bags_table").html(rows);
}

如何使 Ajax 响应生成的表被点击?

【问题讨论】:

    标签: javascript jquery html ajax html-table


    【解决方案1】:

    当您通过代码和动态生成表格时,您应该使用event delegation method

    $(document).on('click','#bags_table tr',function() {
         alert(1)
         alert($(this).attr('id')); //trying to alert id of the clicked row          
    });
    

    【讨论】:

      【解决方案2】:

      试试event delegation.on()

      $(document.body).on('click','#bags_table tr',function () {
         alert(1)
         alert($(this).attr('id')); //trying to alert id of the clicked row          
      });
      

      您的表格行在运行时附加,并且运行时添加的元素无法显示在视图源中,并且您无法将本机事件绑定到这些元素,您需要相同的事件委托。

      这里代替document/document.body你可以有最近的父元素

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-15
        • 1970-01-01
        • 2019-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多