jQuery在线编辑html表格内容

jQuery在线编辑html表格内容

问题描述:

在这张表中onclick我想做出完整的行editable.but与下面的代码能够编辑只有一个时间单元格,当我点击行,完整的单元格tr应该是可编辑的。jQuery在线编辑html表格内容

$("#tableid").on("click", "td", function() { 
 

 
    $(this).parents('tr').css('background-color', 'red'); 
 
    var new = $(this).text(); 
 
    $(this).addClass("editclass"); 
 
    $(this).html("<input type='text' value='" + new + "'/>"); 
 

 
    $(this).children().first().focus(); 
 

 
    $(this).children().first().keypress(function(e) { 
 
    if (e.which == 13) { 
 
     var new1 = $(this).val(); 
 
     $(this).parent().text(new1); 
 
     $(this).parent().removeClass("editclass"); 
 
    } 
 
    }); 
 
    $(this).children().first().blur(function() { 
 
    $(this).parent().text(new); 
 
    $(this).parent().removeClass("editclass"); 
 
    }); 
 
    return false; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table id="tableid"> 
 
    <thead> 
 
    <tr> 
 
     <th>sno</th> 
 
     <th>name</th> 
 
     <th>id</th> 
 
     <th>language</th> 
 
     <th>state</th> 
 
    </tr> 
 
    </thead> 
 
</table>

+0

有在您的示例表中没有'td'。 – Barmar

+0

如果你希望行中的所有TD都是可编辑的,你需要设置'$(this).siblings()'的HTML,而不仅仅是$(this)'。 – Barmar

+0

@Barmar动态获取td值 –

您需要设置所有的兄弟阵的HTML,而不仅仅是一个他们点击。

此外,不要使用new作为变量名,它是一个Javascript保留字。

我为新添加的输入添加了一个click处理程序,用于停止事件冒泡。否则,当你点击一个字段时,它会跳出td,并再次运行处理程序。

$("#tableid").on("click", "td", function() { 
 

 
    $(this).closest('tr').css('background-color', 'red'); 
 
    $(this).siblings().addBack().html(function(i, oldhtml) { 
 
    return "<input type='text' value='" + oldhtml + "'/>"; 
 
    }).addClass("editclass").find("input").keypress(function(e) { 
 
    if (e.which == 13) { 
 
     var new1 = $(this).val(); 
 
     $(this).parent().text(new1); 
 
     $(this).parent().removeClass("editclass"); 
 
    } 
 
    }).blur(function() { 
 
    var new1 = $(this).val(); 
 
    $(this).parent().text(new1); 
 
    $(this).parent().removeClass("editclass"); 
 
    }).click(function(e) { 
 
    e.stopPropagation(); 
 
    }); 
 
    $(this).find("input").focus(); 
 
    return false; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table id="tableid"> 
 
    <thead> 
 
    <tr> 
 
     <th>sno</th> 
 
     <th>name</th> 
 
     <th>id</th> 
 
     <th>language</th> 
 
     <th>state</th> 
 
    </tr> 
 
    <tr> 
 
     <td>1</td> 
 
     <td>Some Name</td> 
 
     <td>ID#1</td> 
 
     <td>English</td> 
 
     <td>New York</td> 
 
    </tr> 
 
    </thead> 
 
</table>

+0

当我编辑td其gvng可编辑td单元格中的完整html –

+0

您是否在末尾添加了'click'处理程序?直到我这样做,我才得到HTML。 – Barmar

+0

而不是将它们更改为'',为什么不使用'contenteditable'属性? – Barmar