如何从jQuery onclick获取数组中价格的X总金额

如何从jQuery onclick获取数组中价格的X总金额,jquery,html,Jquery,Html,我正在尝试制作一个小型的结账系统。我基本上是从数组中获取信息并显示信息。我正在尝试进行实时购物车更新。用户可以选择选择多个产品并将其添加到购物车中。我简化了代码以突出我的问题。我可以拿到价格,没问题。我遇到问题的地方是多次单击事件。因此,当他们点击10欧元时,会增加10欧元的罚款。但我想在10欧元的基础上加上下一项,这样我就可以得到30欧元。最好的方法是什么 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jq

我正在尝试制作一个小型的结账系统。我基本上是从数组中获取信息并显示信息。我正在尝试进行实时购物车更新。用户可以选择选择多个产品并将其添加到购物车中。我简化了代码以突出我的问题。我可以拿到价格,没问题。我遇到问题的地方是多次单击事件。因此,当他们点击10欧元时,会增加10欧元的罚款。但我想在10欧元的基础上加上下一项,这样我就可以得到30欧元。最好的方法是什么

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<?php 

$div_array = array('10','20','30');

foreach($div_array as $test)
{


 ?>
<div class = "container"><!-- The idea here is that this is going to be an image that a user will click on and get the below text once clicked  -->
<div class = "clickme"><h3><a href = "#"><?php echo $test; ?></a></h3> </div> <!-- This is the information I am trying to get -->
</div>
<?php


}
?>
<div class = "cost"></div>

<!-- Logic -->

<script type="text/javascript">

$(document).ready(function(){
$(".container").click(function() {
var x = $(this).index();

var cost = $('.clickme').eq(x).text(); //Gets the cost of the product

$('.cost').html('<h1> This is the result €'+cost+'</h1>');//This is to display the live costs incrementing on each click not just replacing the text

});


}); 
</script>

$(文档).ready(函数(){
$(“.container”)。单击(函数(){
var x=$(this.index();
var cost=$('.clickme').eq(x).text();//获取产品的成本
$('.cost').html('这是结果€'+cost+'');//这是显示每次单击时增加的实时成本,而不仅仅是替换文本
});
}); 

维护总成本变量

$(document).ready(function() {
  var totalcost = 0;
  $(".container").click(function() {
    var x = $(this).index();

    var cost = +$('.clickme').eq(x).text(); //Gets the cost of the product
    totalcost += cost;

    $('.cost').html('<h1> This is the result €' + totalcost + '</h1>'); // will print total cost now

  });
$(文档).ready(函数(){
var总成本=0;
$(“.container”)。单击(函数(){
var x=$(this.index();
var cost=+$('.clickme').eq(x).text();//获取产品的成本
总成本+=成本;
$('.cost').html('这是结果€'+totalcost+'');//现在将打印总成本
});

我更改了您的代码,请参见代码中的注释以了解解释


/*定义函数外部的总计*/
var合计=0;
$(函数(){
/*将函数直接绑定到锚上:*/
$(“.container.clickme a”)。单击(函数(){
/*获取值*/
var cost=parseFloat($(this).text());
/*把它加到总数上*/
总+=成本;
$('.cost').html('这是结果€'+总计+'');
});
});

PHP与您的问题不相关。请发布呈现的HTML,告诉您我要找的内容