【问题标题】:jquery each() iteratonjquery each() 迭代
【发布时间】:2012-10-17 09:55:06
【问题描述】:

我想在按下按钮时将输入值与 p 标签相乘。我的html结构是这样的:

<div class="table">
    <input class="input" type="text" /> 
    <p>10</p>
</div>

<div class="table">
    <input class="input" type="text" />
    <p>20</p>
</div>

<div class="bill"></div> // the result must be displayed in this tag
<button class="button">Calculate</button>

我使用每种方法来选择输入元素,这是我的 jquery 结构:

$(function() {
   function calculate()
   {
      $('input.input').each(function(index) {
      var inputValue = $(this).val();
      var valueP = $(this).next('p').text();
      var result = inputValue * valueP;
      $('.bill').text(result);// displays only last multipled result
      console.log(result); // displays all multipled results
   });
   }

   $('.button').click(function() {
       calculate();
   });
});

我实现了将输入值与 p 标签相乘,但问题是只有最后一个相乘的输入值显示在带有“bill”的类中。但是使用 console.log 看起来不错 此外,“document.write(result)”也可以。我该如何解决这个问题? 顺便说一句,有人可能会说,我怎么能把所有相乘的结果相加! 感谢提前!

【问题讨论】:

    标签: javascript jquery iteration each


    【解决方案1】:

    试试这个demo

    function calculate() {
        var result = 0;
        $('input.input').each(function(index) {
            var inputValue = Number($(this).val());
            var valueP = Number($(this).next('p').text());
            result += inputValue * valueP;
    //as you were adding here it will each time update the .bill
            console.log(result);
        });
        $('.bill').text(result);
    }
    
    $('.button').click(calculate);​
    

    更新

    demo 用于显示除了添加之外的所有计算结果

    function calculate()
    {
       //var result = 0;
      $('input.input').each(function(index) {
      var inputValue = Number($(this).val());
      var valueP = Number($(this).next('p').text());
      var  result = inputValue * valueP;
      $('.bill').append(result+"<br/>");
      console.log(result);
    });
    }
    
    $('.button').click(calculate);​
    

    【讨论】:

    • 感谢您的热情回复。这是添加所有相乘结果的好方法,但对我来说主要问题是除了相加之外,我还想显示所有相乘结果!
    • 为此您可以在.each 循环中使用$('.bill').append(result);
    • 效果很好!谢谢!为什么我不记得“附加”方法。再次感谢
    【解决方案2】:

    请试试这个:

    function calculate() {
        var result = 0;
        $('input.input').each(function(index) {
            var inputValue = Number($(this).val());
            var valueP = Number($(this).next('p').text());
            result += inputValue * valueP;
            $('.bill').append(result);
            console.log(result);
        });
    
    }
    
    $('.button').click(calculate);​
    

    【讨论】:

    • 我得到了答案。还是谢谢你!
    猜你喜欢
    • 2010-12-14
    • 1970-01-01
    • 2014-09-15
    • 2011-09-12
    • 2011-04-09
    • 1970-01-01
    • 2018-07-15
    • 2012-09-24
    相关资源
    最近更新 更多