如何在更改时更新所选选项元素的总和

How to update the sum of selected option elements on change

我想了解为什么总和没有更新。

这是我的下拉列表:

echo "<select name='CPU'>";
while ($row = mysqli_fetch_array($result)) {
    if($row['id']==1)
        echo "<option value='" . $row['id'] . "'a='" . $row['productprice'] 
       . "'>" . $row['productname'] . "</option>";
    else if($row['productstock']>0 && $row['id']>1)
        echo "<option value='" . $row['id'] . "'a='" . $row['productprice'] 
       . "' >" . $row['productname'] . " Price:" . $row['productprice'] . "</option>";
}
echo "</select>";

这是我更新总和的函数:

$('select').change(function(){
    var sum = 0;
    $('select :selected').each(function() {
        sum += Number($(this).attr("a"));
    });
    $("#sum").html(sum);
    //
});

每次调用

$('select').change(function(){

您正在再次初始化 var sum = 0;,这就是它没有添加到先前值的原因。需要把初始化去掉,只在页面加载时初始化一次。

$(document).ready(function(){
   var sum = 0;
   $('select').change(function(){
      $('select :selected').each(function() {
         sum += Number($(this).attr("a"));
      });
   $("#sum").html(sum);
   })
});

>>>Demo<<<