Javascript jQuery使用foreach函数选择所有输入

Javascript jQuery使用foreach函数选择所有输入,javascript,jquery,html,Javascript,Jquery,Html,我有48个输入,对于每一个输入,我需要得到它的值,然后把它加到总和上。目前,我只获取两个输入的值并将其相加,但如何使其成为“foreach函数”更好 $(文档).ready(函数(){ $('.margin.custom输入:第n个子(1)')。更改(函数(){ updateTotal(); }); $('.margin.custom输入:第n个子(2)').change(函数(){ updateTotal(); }); var updateTotal=函数(){ var input1=par

我有48个输入,对于每一个输入,我需要得到它的值,然后把它加到总和上。目前,我只获取两个输入的值并将其相加,但如何使其成为“foreach函数”更好

$(文档).ready(函数(){
$('.margin.custom输入:第n个子(1)')。更改(函数(){
updateTotal();
});
$('.margin.custom输入:第n个子(2)').change(函数(){
updateTotal();
});
var updateTotal=函数(){
var input1=parseInt($('.margin.custom输入:第n个子项(1')).val();
var input2=parseInt($('.margin.custom输入:第n个子项(2')).val();
var总计=输入1+输入2;
$(.marginAttachment”).text(“durchchn.Attachmentniveau=“+total+”mm”);
};
});

jQuery确实具有
foreach
支持,其形式为函数:

var sum = 0;
$('.margin .custom-input').each(function() {
    sum += parseInt($(this).val());
});

每个函数都必须使用jQuery。您的最终代码如下所示

$(document).ready(function() {
   $('.margin .custom-input').change(function() {  
      updateTotal();
   });

   var updateTotal = function () {
        var total = 0;
        $('.margin .custom-input').each(function() {
            total += parseInt($(this).val());
        });

         $(".marginAttachment").text("Durchschn. Attachmentniveau = " + total + "mm");
   };
});
$(document).ready(function() {
   var total = 0

   $('.margin .custom-input').change(function() {  
       total += $(this).val()
      $(".marginAttachment").text("Durchschn. Attachmentniveau = " + total + "mm");
   });

});
或者,直接获取活动输入的值,这样就不需要实现for循环。像这样

$(document).ready(function() {
   $('.margin .custom-input').change(function() {  
      updateTotal();
   });

   var updateTotal = function () {
        var total = 0;
        $('.margin .custom-input').each(function() {
            total += parseInt($(this).val());
        });

         $(".marginAttachment").text("Durchschn. Attachmentniveau = " + total + "mm");
   };
});
$(document).ready(function() {
   var total = 0

   $('.margin .custom-input').change(function() {  
       total += $(this).val()
      $(".marginAttachment").text("Durchschn. Attachmentniveau = " + total + "mm");
   });

});

请展示你在解决问题上的努力,以及这是如何起作用的。