【问题标题】:Jquery : edit a table row does not work on a new rowJquery:编辑表格行不适用于新行
【发布时间】:2015-01-18 14:32:37
【问题描述】:

我正在使用 jQuery 在表格中添加或编辑行。如果我尝试在此处编辑已经存在的行,它可以工作,但如果我添加新行,则编辑不起作用。

我的脚本:

//Add a row
$("#btnadd").click(function(){

$('.table tr:last').after('<tr>' +
    "<td>Name</td>"+    
'</tr>');
});

 //Edit a row (took from a tutorial)
$(function () {
    $("td").dblclick(function () {
        var OriginalContent = $(this).text();

        $(this).addClass("cellEditing");
        $(this).html("<input type='text' value='" + OriginalContent + "' />");
        $(this).children().first().focus();

        $(this).children().first().keypress(function (e) {
            if (e.which == 13) {
                var newContent = $(this).val();
                $(this).parent().text(newContent);
                $(this).parent().removeClass("cellEditing");
            }
        });

    $(this).children().first().blur(function(){
        $(this).parent().text(OriginalContent);
        $(this).parent().removeClass("cellEditing");
    });
    });
});

我对 Jquery 很陌生,所以我很确定我错过了一些明显的东西。

【问题讨论】:

    标签: jquery html-table row


    【解决方案1】:

    $('table').on('click','tr', function(){
        $(this).css('color','green');
    });
    
    $('button').on('click',function(){
        var newRow = $('<tr class="row"><td>New</td><td>Row</td><td>29</td></tr>');
        $('table').append(newRow);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <table style="width:100%">
      <tr>
        <td>Jill</td>
        <td>Smith</td> 
        <td>50</td>
      </tr>
      <tr>
        <td>Eve</td>
        <td>Jackson</td> 
        <td>94</td>
      </tr>
    </table>
    <button>Add</button>

    我认为这是因为点击事件在页面加载时绑定到表格。您在页面加载后输入的任何新行都缺少此事件。现在您的函数在单击 TR(表格行)时被触发。由于加载页面时该(新)表行不存在,因此事件不会绑定到新行。

    您可以通过将点击事件绑定到表格来解决此问题。通过这样做,它会起作用。如果您单击它,我制作了一个小提琴,其中 tr 是绿色的。它也适用于新添加的表格行

    $('table').on('click','tr', function(){
           //do your edits
    });
    

    我认为您在复制中犯了一个小错误,因为您添加行的点击功能没有正确关闭?

    【讨论】:

    • 你说得对,我忘了“});”。感谢您的回答,但它不起作用:使用 $('table') 它让我在只想编辑一行时编辑整个表格。
    猜你喜欢
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多