我的页面上有动态构建的 HTML 表。我使一些单元格可编辑。此外,一个单元格包含基于同一行中的其他两个单元格的计算值。这是我的表格的一部分:
<tr class="mattersRow">
<td class="editableCell hours">0.50</td>
<td class="editableCell rate">170</td>
<td class="editableCell amount">85.00</td>
</tr>
在 jQuery 中,我使单元格可以通过双击进行编辑:
$('.editableCell').dblclick(function (e) {
if ($(this).find('input').length) {
return;
}
var input = $("<input type='text' class='form-control' />")
.val($(this).text());
$(this).empty().append(input);
$(this).find('input')
.focus()
.blur(function (e) {
$(this).parent('td').text(
$(this).val()
);
});
就触发更改事件而言,我扩展了 var() 方法
$(function () {
// Extending the val method so that the change event is triggered when value is changed using the val function.
// caching the val function.
var $valFn = $.fn.val;
$.fn.extend({
val: function () {
// Our custom val function calls the original val and then triggers the change event.
var valCatch = $valFn.apply(this, arguments);
if (arguments.length) {
$(this).change();
}
return valCatch;
}
});
});
现在,当值发生变化时,我会触发此事件:
input.change(function () {
$(this).closest('.amount').val($(this).closest('.hours').val() * $(this).parents('.rate').val());
// This is I can't get value of hours and rate cells...
});
如何获取费率和小时单元格的值,计算并放入金额单元格?
最佳答案
您正确地开始将文本转换为值并对其进行编辑,但在最终计算中您试图获取文本条目的值。为什么不将单元格条目转换为具有可以轻松使用的值的输入字段?例如
<td> <input type='text' class="editableCell hours" size='5' value='0.50'></td>
<td> <input type='text' class="editableCell rate" size='3' value='170'></td>
<td> <input type='text' class="editableCell amount" size='8' value='85.00'></td>
关于javascript - 更改一列时如何更新 HTML 表格行中的单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20053843/