首页 > 解决方案 > 没有从以编程方式构建的表中触发 onclick 事件

问题描述

我有一个表,它以编程方式添加了一个 onclick 事件,该事件调用具有我要编辑的行的 id 的特定 javascript 函数。但是它没有被调用。我尝试通过添加一个类并尝试在那里获取一些东西来更改按钮,但它不起作用。这曾经有效,我无法弄清楚为什么或如何解决它。

function buildTable() {
$.ajax({
    url: "getTable.php",
    dataType: "json",
    success: function(result) {
        if (result != null) {
            $('#measurements tbody tr').remove();
            result.forEach(function (measurement) {
                var message = "<tr><td>" + dateFromtimestamp(measurement.weigh_date) + "</td>";;
                message += "<td>" + measurement.weight + "</td>";
                message += "<td><input type='hidden' value='" + measurement.id + "'>" + measurement.waist + "</td>";
                message += "<td>" + measurement.upperBp + "</td>";
                message += "<td>" + measurement.lowerBp + "</td>";
                message += "<td>" + measurement.comment + "</td>";
                message += "<td><button type='button' class='btn btn-outline-warning' onlick='editRow(" + measurement.id + ")'>";
                message += "<span class='glyphicon glyphicon-pencil'></span></button>&nbsp;";
                message += "<button type='button' class='btn btn-outline-danger' onlick='removeRow(" + measurement.id + ")'>";
                message += "<span class='glyphicon glyphicon-remove'></span></button></td></tr>";
                $('#measurements').append(message);
            });
        }
    }
});

}

以下是它被添加到的 HTML 表:

<div class="panel panel-info">
<div class="panel-heading text-center">Past measurements</div>
<div class="panel-body">
    <table class="table table-striped" id="measurements">
        <thead class="thead-dark">
        <th scope="col">Date</th>
        <th scope="col">Weight</th>
        <th scope="col">Waist</th>
        <th scope="col">Systolic (Upper)</th>
        <th scope="col">Diastolic (Lower)</th>
        <th scope="col">Comment</th>
        <th scope="col">Action</th>
    </thead>
        <tbody>
    </tbody>
     </table>
     <div class="row">&nbsp;</div>
 </div>
 </div>

这是有问题的编辑功能,以防我错过参数签名的某些内容:

function editRow(id) {
    $.ajax({
        url: "getMeasurement.php",
        type: "post",
        dataType: "json",
        data: {
            "id": id
        },
        success: function(data) {
            if (data != null) {
            data.forEach(function(result){
                var id = result.id;
                $('#editMeasurement').modal('show');
                $('#editupper').val(result.upperBp);
                $('#editlower').val(result.lowerBp);
                    $('#editwaist').val(result.waist);
                    $('#editweight').val(result.weight);
                    $('#editcomment').text(result.comment);
                    $('#editRowHidden').val(id);
        });             
    }
    }   
});
}

我尝试通过添加一个类来更改按钮:并尝试使用 $('.editRow').on("click", function() {} 事件来捕获事件,结果相同。

标签: javascriptjqueryhtml

解决方案


感谢kmgt。如果它是一条蛇,它会咬我。必须使用“onclick”而不是“onlick”。


推荐阅读