javascript 使 html 表可编辑,并在该行中的文本更改时启用每行按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17246648/
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
Make html table editable, and enable a per-row button when text changes in that row
提问by jonderry
I have an html table that looks like the following:
我有一个如下所示的 html 表:
<table id="tree">
<tr id="foo-1">
<td>fooId1</td>
<td>fooName1</td>
<td>fooCsv1</td>
<td><button id="button-1" type="button" disabled>Save</button></td>
</tr>
<tr id="foo-2">
<td>fooId2</td>
<td>fooName2</td>
<td>fooCsv2</td>
<td><button id="button-2" type="button" disabled>Save</button></td>
</tr>
</table>
There are two modifications I want to do to this table:
我想对这个表做两个修改:
-First, I want to make the fooName and fooCsv td elements editable (there are actually a couple more editable columns, but I'm just using two to make this example simpler). I know that I can simply put an input inside the td element and set the value, but was wondering if there's a simpler way.
- 首先,我想让 fooName 和 fooCsv td 元素可编辑(实际上还有几个可编辑的列,但我只是使用两个来使这个例子更简单)。我知道我可以简单地将输入放入 td 元素并设置值,但想知道是否有更简单的方法。
-Second, I want the Save button in each row to become enabled when a user changes the text in that row via typing/copy-paste/etc. I've googled and found that I might be able to do this by adding a handler for an input event, but I'm not sure of the simplest way to incorporate this, and I'm not sure if it has ramifications for the first task I have.
- 其次,当用户通过键入/复制粘贴/等更改该行中的文本时,我希望每行中的“保存”按钮变为启用状态。我在谷歌上搜索并发现我可以通过为输入事件添加处理程序来做到这一点,但我不确定合并它的最简单方法,我不确定它是否对第一个产生影响我有任务。
I think this should be easy if I knew much about html and javascript, but I don't, so does anyone know a simple way to achieve what I'm trying to do?
我认为如果我对 html 和 javascript 了解很多,这应该很容易,但我不知道,所以有人知道实现我想要做的事情的简单方法吗?
回答by raam86
<td contenteditable="true">fooName1</td>
And use what ever you want to post the table HTML
并使用您想要发布表格 HTML 的任何内容
edit:
编辑:
//Listen to blur event in contenteditable td elements
$('td[contenteditable=true]').blur(function () {
$(this).parent('tr').find('button').removeAttr('disabled');
});
//When a button is clicked find the nearest contenteditable td //element(s) and push their
text content to an array, this array is later being posted.
$('button').click(function () {
var contents = $(this).parents().find('td[contenteditable=true]');
var contentArray = [];
for (i = 0; i < contents.length; i++) {
contentArray[i] = contents[i].innerHTML;
}
$.post("test.php", contentArray);
});