使用 Jquery,用新的一行替换表中的一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7517519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:57:11  来源:igfitidea点击:

Using Jquery, replace one row in table with a new one

jqueryhtml-table

提问by Steve Walsh

Say I have a table:

假设我有一张桌子:

<table id="mytable">
      <tr class="old_row"><td>1</td><td>2</td><td class="edit">Edit</td></tr>
      <tr class="old_row"><td>1</td><td>2</td><td class="edit">Edit</td></tr>
      <tr class="old_row"><td>1</td><td>2</td><td class="edit">Edit</td></tr>
</table>

I want to click on the <td>Edit</td>cell and use jquery to replace the entire row with a new row with more content, e.g.

我想单击<td>Edit</td>单元格并使用 jquery 将整行替换为具有更多内容的新行,例如

    $(document).ready(function() {

        $('#mytable .edit').click( function() {

            var tr = $(this).parent();
            var new_row = '<tr class="new_row"><td>3</td><td>4</td><td>Save</td></tr>'
            // code to replace this row with the new_row
        });

    } );

Any idea how this could be done?

知道如何做到这一点吗?

回答by maxedison

$(document).ready(function() {

    $('#mytable .edit').click( function() {

        var new_row = '<tr class="new_row"><td>3</td><td>4</td><td>Save</td></tr>'
        $(this).parent().replaceWith(new_row);
    });

} );

回答by John Hartsock

Use jQuery.replaceWith()

使用jQuery.replaceWith()

$(document).ready(function() {
  $('#mytable .edit').click( function() {
    var tr = $(this).parent();
    var new_row = '<tr class="new_row"><td>3</td><td>4</td><td>Save</td></tr>';
    tr.replaceWith(new_row);
  });
});

回答by Dennis

jQuery's replaceWith(). Example:

jQuery 的replaceWith(). 例子:

$(document).ready(function() {
    $('#mytable .edit').click( function() {

        var tr = $(this).parent();
        var new_row = '<tr class="new_row"><td>3</td><td>4</td><td>Save</td></tr>'
        tr.replaceWith(new_row); // code to replace this row with the new_row
    });
} );

回答by Korvin Szanto

http://jsfiddle.net/hAvyv/

http://jsfiddle.net/hAvyv/

$('.edit').click(function(){
    $(this).parent().removeClass('old_row').addClass('new_row').html('<td>3</td><td>4</td><td>Save</td>');
});