簡體   English   中英

更改一列時如何更新HTML表格行中的單元格?

[英]How to update cells in the HTML Table row when change one column?

我的頁面上有動態生成的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>

最接近的函數沿dom樹向上移動,以獲取元素的父代,類似於父代函數。 您的td和hour td元素不是父元素,因此不會找到它們。 您可以嘗試獲取輸入父母的兄弟姐妹。

$(this).parent().siblings(".rate");

同樣,看起來您刪除了模糊的輸入,因此您將需要獲取文本而不是值。

$(this).parent().siblings(".rate").text();   

終於,幾個小時后,我找到了一種正確的方法=)因此,基本上不需要觸發變更事件,可以在將輸入替換為td文本后重新計算值,只需記住輸入處於活動狀態時的當前行即可。 jQuery代碼:

$(this).find('input')
     .focus()
     .blur(function (e) {
          var row = $(this).closest('tr'); // Remember row
          $(this).parent('td').text($(this).val());
          row.find('.amount').text(parseFloat(row.find('.rate').text()) * parseFloat(row.find('.hours').text())); // Calculate and put in the amount cell
     });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM