我正在开发一个项目,该项目要求我在单击另一个表中的相应行时使表中的单元格可编辑。我遇到的问题是,我无法让它只使可更新表中的单行可编辑,而是使每行的每个单元格都可编辑。
这是 jsfiddle 上的一个示例,演示了该问题:http://jsfiddle.net/z9qtH/24/
在此示例中,如果您单击顶部表格中的“第 1 行”,则下表的第一行的单元格内容应替换为输入。相反,底部表格中的两行都变得可编辑。
代码
HTML:
<table border="1">
<tr>
<td class="editable">Row 1</td>
</tr>
<tr>
<td>Row 2</td>
</tr>
</table>
<table class="updateable" border="1">
<tr>
<td>1 - 1</td>
<td>1 - 2</td>
<td>1 - 3</td>
</tr>
<tr>
<td>2 - 1</td>
<td>2 - 2</td>
<td>2 - 3</td>
</tr>
</table>
Javascript:
function replaceRowCellContentsWithInput(row) {
$("td", row).each(function() {
$(this).html('<input type="text" value="' + $(this).html() + '" />');
});
}
$(document).ready(function() {
$("td.editable").click(function() {
var cell = $(this);
var rowIndex = cell.parent().index();
var table = $("table.updateable");
replaceRowCellContentsWithInput(table.children(rowIndex));
});
});
最佳答案
您的行:table.children(rowIndex)
选择(可能的thead
)和tbody
元素。即使它们没有出现在您的 HTML 中,浏览器也始终会插入 tbody
。
如果您将其替换为(例如)$('tr', table)[rowIndex]
,您确定您实际上正在选择表内的行。
关于javascript - 在 jQuery 中使用上下文和 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6858232/