简体   繁体   English

单击按钮时如何将表中的某些td转换为文本框

[英]How to convert some td from a table into textbox when a button is clicked

I have a table with 4 rows and 4 column. 我有一张有4行4列的表。 Also I have a button called edit. 我还有一个名为“编辑”的按钮。 Now when I click on that button, I want the last two columns of the table to be changed into textboxes with values of those columns and finally a save button to save them. 现在,当我单击该按钮时,我希望将表的最后两列更改为具有这些列的值的文本框,最后是一个保存按钮以保存它们。

I do not have any identification for individual tds so facing a little problem in changing them into textboxes. 我没有任何单个tds的标识,因此在将其更改为文本框时会遇到一些问题。

In html5 there is a feature that is called content editable. 在html5中,有一个称为内容可编辑的功能。

you can make one html element editable with just adding one attribute to the html element 您只需将一个属性添加到html元素即可使一个html元素可编辑

take an example of td element, if you want to make it editable, just add one "contenteditable" attribute to the td element 以td元素为例,如果要使其可编辑,只需向td元素添加一个“ contenteditable”属性

<td contenteditable>Some String</td>

in jQuery you can add the contenteditable attribute like this 在jQuery中,您可以像这样添加contenteditable属性

$("td#target").attr("contenteditable", "");

After making it contenteditable you have to click on the html element, it will appear as an editable html element. 使其内容可编辑后,您必须单击html元素,它将显示为可编辑的html元素。

Hope this is helpful. 希望这会有所帮助。

use .replaceWith() in jquery Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. 在jquery中使用.replaceWith()用提供的新内容替换匹配元素集中的每个元素,并返回被删除的元素集。

$('tr td').slice(-2).each(function(){

  $(this).replaceWith( $("<input/>",{value:$(this).text(),type:"text"}) );
   //OR
    // $(this).replaceWith( '<input type="text" value="'+$(this).text()+'">');
});

note in slice :Use negative numbers to select from the end of an array 切片中的注释:使用负数从数组末尾选择

DEMO 演示

You have To use nth-child Selector to Get the required td element 您必须使用nth-child选择器来获取所需的td元素

Look Here: 看这里:

<table>
<tr><td>John</td><td>John</td><td>John</td><td>John</td></tr>
<tr><td>Karl</td><td>John</td><td>John</td><td>John</td></tr>
<tr><td>Brandon</td><td>John</td><td>John</td><td>John</td></tr>
<tr><td>Benjamin</td><td>John</td><td>John</td><td>John</td></tr>
</table>

You Can Get Last 2 td Following Way 您可以按照以下方式获得最后2 td

 $( "tr td:nth-child(3)" ).html( "<input />" );
 $( "tr td:nth-child(4)" ).html( "<input />" );

Fiddle: 小提琴:

Fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM