0

次の問題があります。

次の入力の値が変更されると、フィールド #result が変更されます。

 <input type="text" data-original-value="320" value="320" name="value1" id="value1" class="restorable">
 <input type="text" data-original-value="125" value="125" name="value2" id="value2" class="restorable">
 <input type="text" data-original-value="0.5" value="0.5" name="value3" id="value3" class="restorable">


    (function ($) {
     $(document).ready(function () {
         $('#coverage').keyup(function () {
             var raw = $('#value1').text()-( $('#value2').text()* $('#value3').text());
             var fixed = raw.toFixed();
             $('#result').text(fixed);
         });
     });
 }(jQuery));

1つの値を変更すると機能しますが、それを可能にする方法

  • #結果はページの読み込み時に計算されます
  • # value1 または value2 または value3 が変更されると、結果が更新されます
4

2 に答える 2

2

私はお勧めします:

// bind the 'keyup' event to the elements:
$('input.restorable').keyup(function(){
    // set the text of the '#result' element:
    $('#result').text(function(){
        // initialise a variable to hold the value:
        var total = 0;
        // get the relevant sibling 'input' elements, and iterate over them:
        $(this).siblings('input.restorable').each(function(){
            /* add the value, using parseFloat() to make it a numeric value,
               to that total variable: */
            total += parseFloat(this.value);
        })
        // set the text to the value of that variable
        return total;
    });
// trigger the function bound on 'keyup' by triggering a 'keyup' event:
}).trigger('keyup');

JS フィドルのデモ

参考文献:

于 2013-06-04T20:55:44.740 に答える
0

計算を行う jQuery 関数を作成し、各フィールドにイベント リスナーをアタッチする必要があります。

$('#value1, #value2, #value3').on('keyup', function() {
    calculate();
});

var calculate = function() {
    var result = $('#value1').val() - ($('#value2').val() * $('#value3').val());
    $('#result').text(result.toFixed(2));
};

ただし、計算の一部としてそれらを識別する共通のクラスまたはデータ属性を HTML 要素に追加することで、これをリファクタリングします。そうすれば、jQuery スクリプトでそれらの参照をハードコーディングする必要がなくなります。

また、ユーザーが実際に数値を入力していることを確認する必要もあります。

于 2013-06-04T20:54:13.960 に答える