如果我修改列a
或b
中的单元格,则列c
中的值应该更改。但是现在c
中所有列的值都在变化。但我只需要在我进行更改的特定行中更改值。
$(".table").each(function () {
$(this).find('.total').data('total',text);
$(this).find('.total').text(text);
});
// Editable Cells
$(document).on('click', '.editable', function (event) {
if ($(this).children("input").length > 0)
return false;
var tdObj = $(this);
var preText = tdObj.html();
var inputObj = $("<input type='text' />");
tdObj.html("");
inputObj.width(tdObj.width())
.height(tdObj.height())
.css({
border: "0px",
height: "25px",
width: "50%",
})
.val(preText)
.appendTo(tdObj)
.trigger("focus")
.trigger("select");
inputObj.keyup(function (event) {
if (13 == event.which) { // press ENTER-key
var text = $(this).val();
tdObj.html(text);
$("table").each(function () {
$(this).find('.total').text(text);
});
} else if (27 == event.which) { // press ESC-key
tdObj.html(preText);
}
});
inputObj.click(function () {
return false;
});
inputObj.blur(function (event) {
tdObj.html(preText);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:50%">
<tr>
<th>a</th>
<th>b</th>
<th>c</th>
</tr>
<tr>
<td class="editable">20</td>
<td class="editable">30</td>
<td class="total">50</td>
</tr>
<tr>
<td class="editable">10</td>
<td class="editable">20</td>
<td class="total">94</td>
</tr>
</table>
答案 0 :(得分:1)
使用.closest('tr').find('.total')
$(document).ready(function() {
$('.editable').keyup(function() {
var sum = parseInt($(this).text())
// select next .editable, that is not currently selected
+ parseInt($(this).closest('tr').find('.editable').not(this).text());
$(this).closest('tr').find('.total').text(sum);
})
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:50%">
<tr>
<th>a</th>
<th>b</th>
<th>c</th>
</tr>
<tr>
<td class="editable" contenteditable="true">20</td>
<td class="editable" contenteditable="true">30</td>
<td class="total">50</td>
</tr>
<tr>
<td class="editable" contenteditable="true">10</td>
<td class="editable" contenteditable="true">20</td>
<td class="total">94</td>
</tr>
</table>
&#13;