簡體   English   中英

jQuery-克隆元素的總和不適用於功能輸入

[英]Jquery - Sum of cloned elements won't work with input from function

這是我的代碼:

$(document).ready(function() {
  $('#clone').click(function() {
    var target = $(this).closest('.groupcontainer');
    target.clone(true, true).insertAfter(target);
  });

  $('.input').on('input',function(){
    $(this).parent().children('.grouptotal').val($(this).val() * $(this).parent().children('.input2').val());
  });

  $('.input2').on('input', function(){
    $(this).parent().children('.grouptotal').val($(this).val() * $(this).parent().children('.input').val());
  });
});  

$(document).on('change', '.grouptotal', function(){
  var sum = 0;
    $('.grouptotal').each(function(){
    sum += +$(this).val();
    });
    $('#subtotal').val(sum);
});

我的問題是,我需要#subtotal添加的每個實例.grouptotal ,但#subtotal當它到達它的輸入來自未更新

$('.input').on('input',function(){
  $(this).parent().children('.grouptotal').val($(this).val() * 
  $(this).parent().children('.input2').val());
  });

$('.input2').on('input', function(){
  $(this).parent().children('.grouptotal').val($(this).val() *   
  $(this).parent().children('.input').val());
  });

如果我將數字手動放在.grouptotal#subtotal將更新。 有人可以向我解釋我所缺少的嗎?

這是小提琴 它看起來有些草率,但是卻給出了主意。

數量*系統將自動更新我的.grouptotal

如何使#subtotal接受.grouptotal並自動添加它們? 我試過將$(document).on('change', '.grouptotal', function(){ “ change”更改為'input'和其他幾個,但是沒有運氣。

同樣,如果單擊#clone按鈕以復制組,則它必須能夠正常工作。

使用val('value')以編程方式設置值時,不會觸發change事件,您必須實際觸發它

$(this).parent().children('.grouptotal').val( $(this).val() ).trigger('change')

讓我們再試一次。 顯然,以編程方式更改組總計值不會觸發更改事件。 我本以為會,所以您的代碼對我來說看起來很正確。 為了解決這個問題,我添加了一個顯式觸發器“ .grouptotal”。 您可以在這里看到小提琴

只需添加代碼:

('.grouptotal').change();

你們兩個處理程序的總和是輸入的總和。 可能不是您要尋找的解決方案,但它似乎有效

暫無
暫無

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

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