我正在尝试对附加的项目做一些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检索所有值,并处理添加的成本和卡路里信息,但与追加它将是更快的初始响应,使网站看起来更快。
这是愚蠢的差事吗?
发布于 2015-09-14 13:43:10
你可以这样做
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();
});
}
});https://stackoverflow.com/questions/32557621
复制相似问题