【问题标题】:Append to a table when tbody is absent and how to make all existing jqueries work for that row当 tbody 不存在时附加到表以及如何使所有现有的 jquery 为该行工作
【发布时间】:2013-07-05 15:39:27
【问题描述】:

我有以下 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);
    }
}

【问题讨论】:

  • 使用模板方法而不是克隆最后一个 tr。
  • 您能详细说明一下吗?
  • 好的。首先你的声明Question is how do I go about adding a column to 'tbody' when their are no rows.你的意思是行而不是列,对吧?
  • 是的。我进行了编辑。
  • 好的,我会为你准备一个样品。

标签: javascript jquery


【解决方案1】:

双击事件对新添加的行不起作用的原因是您在元素存在之前绑定了单击事件。尝试使用这种样式绑定(事件委托是术语):

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

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

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

【讨论】:

  • 你能解释一下为什么一个会比另一个更有效吗?我没有尝试过,但也许它会像通常在 stackoverflow 的专家帮助下一样工作,但如果我有一些原因说明为什么会发生这种情况,我会感觉更好。
  • @SilentPro -- 正如我在答案中所说,您当前的选择器等待(大概在 DOM 就绪语句中)等待页面准备好,然后绑定到您的 td 元素,这很好。现在您正在添加新的td 元素,但由于这些元素在 DOM 中还没有准备好,因此他们不知道应该为它们分配一个点击事件。这就是事件委托的用武之地,这个新的选择器基本上是说,点击#datatable 上的任意位置,如果它恰好是td,我会发火!
  • 所以我应该把它从 $(document).ready(function(){});阻止??
  • @SilentPro -- 保留它,我们仍然将此处理程序绑定到#datatable 元素,因此页面仍然必须等待该元素呈现。
  • 谢谢。关于另一件事,我认为我真的必须编写整个类和样式。
【解决方案2】:

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

假设你的桌子是这样的:

<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.
    });

});

Demo

要添加偶数/奇数样式,您可以使用 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";
});

Demo

【讨论】:

  • 非常感谢。这是一个更好、更优雅的解决方案。我的 tr 元素还有一件事,如果它是偶数行,它有一个类,即使其他类是奇数(基本上是用于 css)
  • 好的。如果你愿意,你根本不需要添加一个类,我可以为你只用 css 编写。
  • @SilentPro 检查这个你可以用 css 做。 jsbin.com/orimeh/4/edit如果您坚持要添加课程,请告诉我我们可以添加它。
  • @SilentPro 使用 append 而不是 after,查看我的更新和演示代码。
  • 我知道我可以做到,但表格是由 django-tables2 生成的,我不编写自己的 css。所以我想我确实需要这门课?
猜你喜欢
  • 2017-06-11
  • 2018-04-06
  • 2021-12-01
  • 1970-01-01
  • 2023-04-11
  • 2020-10-05
  • 2012-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多