javascript - 更改一列时如何更新 HTML 表格行中的单元格?

标签 javascript jquery html-table

我的页面上有动态构建的 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/

相关文章:

javascript - 如何使用 npm jquery 模块?

html - 如何将 table 放在 table 里面?

javascript - 使用slideDown()向jquery-datatable添加一行?

javascript - $.inArray 只检查 jQuery 中数组的最后一个索引

MySQL 使用许多 'like' 运算符进行搜索 : is there a better way?

html - 如何在表中选择包含 colspans 的列?

javascript - 如何在标签strong中设置文本?

javascript - 如何从 TypeScript NodeJS 应用程序中的 CommonJS 模块导出 Mongoose 模型

javascript - 如何从轮播中获取id并显示特定图像的信息?

javascript - D3嵌套和对象遍历