jQuery -在元素属性上执行加法


jQuery - Performing Addition on element attributes

我正在尝试对附加项做一些jquery添加,我想知道这是否是一个好主意以及如何实现它。

场景:

我正在生成一个可以添加到项目中的配料表。

<ul id="greens" class="card-content-ingredients" style="list-style-type: none;">
  <?php foreach ( $greens as $grn ): ?>
    <li value="<?php echo $grn['price']; ?>" id="<?php echo $grn['id']; ?>" cal="<?php echo $grn['nutritionix_cal']; ?>">
      <input type="hidden" class="item_id" value="<?php echo $grn['id']; ?>" name="greens" /> 
      <span class="item-name-small"><?php echo $grn['name']; ?></span>
      <span class="item-description-menu"><?php echo $grn['description']; ?></span>
      <span class="content-right"></span>
    </li>
  <?php endforeach; ?>
</ul>

每当客户单击其中一个项目时,我将该项目附加到另一个div并执行AJAX调用以进行服务器端操作:

<script> <!-- Appending the DIV -->
    $(function (){
      $('ul.card-content-ingredients li').click(function(){
        $('#scroll-2 ul').append($(this));
      })
    });
  </script>
  <script> <!-- AJAX -->
    $(document).ready(function(){
      $('ul.card-content-ingredients li').click(function(){
        var id = $(this).attr('id');
        var value = $(this).attr('value');
        var cal= $(this).attr('cal');
        $.ajax({
          url: "add-to-cart.php",
          type: "POST",
          dataType: "json",
          data: {'id' : id, 'value' : value, 'cal' : cal },
          success: function() {}
        });
      });
    });
  </script>

我想知道的是,在附加步骤中,我是否有办法对输入变量执行加法?

如果DIV是这样写的:

<div class="pure-u-1 pure-u-md-3-5 pure-u-lg-3-5 content-left">
  <div id="scroll-2" class="card">
    <span class="is-center">
    <?php echo substr($menu_item['name'], 0, -6); ?><br />
    <?php echo CURRENCY . $menu_item['price'] . " - Cal: " . $menu_item['nutritionix_cal']; ?>
    </span>
    <ul style="list-style-type: none;">
    </ul>
    <input id="calories" type="text" value="0" size="1" name="calories" disabled>

  </div> <!-- END CARD -->
</div> <!-- END RIGHT SIDE DISPLAY -->

那么当元素从左到右添加到div时,我如何执行加法来将cal属性添加到Calories的输入框中呢?

目前,我在PHP检索所有值并处理成本和热量信息的添加后返回值,但有了附加,初始响应会更快,使网站"看起来"更快。

这是徒劳的吗?

你可以这样做

var totalcalories;
$("[name='calories']").each(function(){
    totalcalories = totalcalories + $(this).val();
});

在ajax的成功函数中,因此ajax函数将更新为

var totalcalories;
$.ajax({
    url: "add-to-cart.php",
    type: "POST",
    dataType: "json",
    data: {'id' : id, 'value' : value, 'cal' : cal },
    success: function() {
        $("[name='calories']").each(function(){
            totalcalories = totalcalories + $(this).val();
        });
    }
});