当 tbody 不存在时追加到表中,以及如何使所有现有 jquery 适用于该行

Append to a table when tbody is absent and how to make all existing jqueries work for that row

本文关键字:何使所 jquery 适用于 不存在 tbody 追加      更新时间:2023-09-26

我有以下jquery根据用户交互和从服务器接收的数据动态附加到表中。现在,表中的每一列都有一些特定的类和一些样式属性,例如列 itemId 被隐藏等。如果我已经有一行,我的动态添加工作正常,但如果它没有,它只会添加另一个标题行,我可以理解这是因为我的代码复制了最后一个 tr 元素。问题是当没有行时,我如何向"tbody"添加一行。

    function responseTopicAdded(data) {
        $('#dialog-modal').dialog('close');
        rowcopy = $('#datatable tr:last').clone();
        rowcopy.children().each(function() {
            switch($(this).attr('class')) {
                case 'Name':
                    $(this).html(data.Name);
                    break;
                case 'Description':
                    $(this).html(data.Description);
                    break;
                case 'Icon':
                    $(this).html('<img src='+ data.Icon +'/>');
                    break;
                case 'itemId':
                    $(this).html(data.itemId);
            }
        });
        $('#datatable tr:last').after($(rowcopy));
    }
我的

第二个问题是我的表格单元格响应双击。但是新添加的行永远不会响应(即使有以前的行并且该行是正常添加的(。

为什么侦听器不处理新行?

我的听众是这样的:

$(document).ready(function() {
    try {
        $("td").dblclick(function() {
            // ... my code goes here
    }catch(a){
        alert(a);
    }
}

双击事件在新添加的行上不起作用的原因是,您在元素存在之前绑定了单击事件。尝试使用此样式进行绑定(事件委派是术语(:

$("#datatable").on("dblclick", "td", function() { //do stuff });

根据在不存在时添加tbody,只需检查是否存在:

if ($("#datatable tbody").length) { //it exists! } else { //it doesnt exist! }

您可以使用模板方法在需要时为要克隆的表行创建模板。

假设你的表是这样的:

<table id="datatable">
    <thead>
          <tr><th>Name</th>
          <th>Description</th>
          <th>icon</th>
          <th>itemID</th></tr>
    </thead>
   <tbody></tbody>
</table>

填充时:

//Create the template here// or keep it in HTML itself in a hidden div or something.
var template = $("<tr><td class='Name'></td><td class='Description'></td><td class='Icon'></td><td class='itemId'></td></tr>");
$(function () {
var newRow = $(template).clone(); //Clone the template
//just an initial load
newRow.find('.Name').text('AAA');
newRow.find('.Description').text('Some Description');
newRow.find('.Icon').text('Some Icon');
newRow.find('.itemId').text('1234');
//Initially clone
$('#datatable').find('tbody').append(newRow);
    //register the handler using event delegation
    $('#datatable tbody').on('click', 'tr', function () {
        alert('clicked on ' + $(this).find('.Name').text());
    });
    $('#addNew').on('click', function () {
        var rowcopy = $(template).clone(); //Clone the template
        var data = {
            Name: 'BBB',
            Description: 'Some Description',
            Icon: 'http://placehold.it/32x32',
            itemId: '45676'
        };
       //Set the Css class name based on even odd row
       rowcopy.addClass(function(){
        return $('#datatable tbody tr').length % 2 == 0 ? "odd" : "even";
       });
        rowcopy.children().each(function () {
            switch ($(this).attr('class')) {
                case 'Name':
                    $(this).html(data.Name);
                    break;
                case 'Description':
                    $(this).html(data.Description);
                    break;
                case 'Icon':
                    $(this).html('<img src=' + data.Icon + '/>');
                    break;
                case 'itemId':
                    $(this).html(data.itemId);
            }
        });
        $('#datatable tbody').append($(rowcopy)); //Append it to the tbody.
    });
});

演示

要添加偶数/奇数样式,您可以使用 css 本身。

#datatable tbody tr:nth-child(odd) {
    background-color:#cecece;
}
#datatable tbody tr:nth-child(even) {
    background-color:yellow;
}

如果不是,你想用类来做,那么:

rowcopy.addClass(function(){
            return $('#datatable tbody tr').length % 2 == 0 ? "odd" : "even";
});

演示