更改变量值后,数据属性不会更改

时间:2019-04-30 15:56:09

标签: javascript jquery

这不是重复的原因,因为我使用.data()而不是.attr()喜欢附加的建议

我需要在更新变量时更改数据属性值。我正在创建一个与折扣字段相关的下拉列表,并且需要更新<option>标记中的text和data属性。

相关部分如下:

$(function() {
  $("#plan-options").change(function() {
    var moneyAmount = $(this).find('option:selected').data('amount');
    $("#selected-price").text("$" + moneyAmount);
    $("#purchase-warning").toggle();
    $(".default-encouragement").toggle();
  });
});

#plan-options是一个<select>标记,其中<option>个具有数据属性。

之后:

...
let selected = $("select option:selected");
let selectedAmount = selected.data("amount");
let selectedStr = selected.text();
let amountOffMoney = (data.amount_off / 100).toFixed(2);
if (data.percent_off != null) {
    selectedAmount = selectedAmount * (100 - data.percent_off) / 100
} else if (data.amount_off != null) {
    selectedAmount = selectedAmount - amountOffMoney;
    // this variable doesn't update - why?
    $("select option:selected").data("amount", selectedAmount);
} else {
    alert("Someting wrong happened!");
    return;
}

最相关的部分在这里:

selectedAmount = selectedAmount - amountOffMoney;
$("select option:selected").data("amount", selectedAmount);

我的期望是我为selectedAmount分配了一个新值,并且将data属性更改为selectedAmount应该会更改为新的分配,但是这没有发生。该值保持不变。

是因为它是let吗?是范围问题吗?

完整代码片段:

$(function() {
  $("#plan-options").change(function() {
    var moneyAmount = $(this).find('option:selected').data('amount');
    $("#selected-price").text("$" + moneyAmount);
    $("#purchase-warning").toggle();
    $(".default-encouragement").toggle();
  });
});
...
jQuery(function ($) {
          $(document).on("click",'.apply_coupon', function (e) {
            e.preventDefault();
            let plan = $('select[name="plan"]').val();
            let coupon = $('input[name="coupon"]').val();
            $.get('/premium/coupon/', {
              coupon: coupon,
              plan: plan
            }, function (data) {
              console.log("got data from calling coupon api:", data)
              if (data.success) {
                //discounted amount display handling
                let selected = $("select option:selected");
                let selectedAmount = selected.data("amount");
                let selectedStr = selected.text();
                let amountOffMoney = (data.amount_off / 100).toFixed(2);
                if (data.percent_off != null) {
                  selectedAmount = selectedAmount * (100 - data.percent_off) / 100
                } else if (data.amount_off != null) {
                  selectedAmount = selectedAmount - amountOffMoney;
                  console.log(selectedAmount);
                  $("#plan-options option:selected").data("amount", selectedAmount);
                } else {
                  alert("Someting wrong happened!");
                  return;
                }

                let regex = /\d+\.*\d*/;
                let newStr = selectedStr.replace(regex, selectedAmount.toString());
                selected.text(newStr);

                $('.apply_coupon').text("Remove");
                $('.apply_coupon').addClass("remove_coupon").removeClass('apply_coupon');
                $('input[name="couponVerified"]').val(1);
                $('input[name="coupon"]').hide();
                $('.coupon-results').show();
                $('.coupon-results__code').text(data.name);
                $('.coupon-results__info').text("$" + amountOffMoney + " off " + data.duration);
                $("#selected-price").text("$" + selectedAmount);
              } else {
                alert(data.message);
              }
            })
          });

          $(document).on('click','.remove_coupon', function (e) {
            e.preventDefault();
            $.get('/premium/coupon/remove/', function (data) {
              if (data.success) {
                //discounted amount reverting handling
                let selected = $("select option:selected");
                let selectedAmount = selected.data("amount");
                let selectedStr = selected.text();
                let regex = /\d+\.*\d*/;
                let newStr = selectedStr.replace(regex, selectedAmount.toString());
                selected.text(newStr);
                $('.remove_coupon').text("apply");
                $('.remove_coupon').addClass("apply_coupon").removeClass('remove_coupon');
                $('input[name="couponVerified"]').val(0);
                $('input[name="coupon"]').show();
                $('.coupon-results').hide();
                $("#selected-price").text("$" + selectedAmount);
              }
            });
          });
        });

1 个答案:

答案 0 :(得分:0)

您似乎正在指定data.amount_off的变量data.percent_offundefined?我假设这些也应该是data标签上的<option>属性?以下代码段在select框值更改时调用测试函数,以使用data属性触发您的值计算。请让我知道,如果你有任何问题。 请注意,从$ 15.00 option切换回默认的“ Select” option,然后再回到$ 15.00 option会每次更新data-amount的值。 / strong>

$(function() {
  $("#plan-options").change(function() {
    var moneyAmount = $(this).find('option:selected').data('amount');

    $("#selected-price").text("");
    $("#purchase-warning").toggle();
    $(".default-encouragement").toggle();

    // call code function below for testing
    if (moneyAmount > 0) {
      // Amount data attribute value on select
      console.log('current data-amount value: ' + moneyAmount);
      $("#selected-price").text("$" + moneyAmount);
      testDataAttr();
    }
  });
});

function testDataAttr() {
  let selected = $("#plan-options option:selected");
  let selectedAmount = selected.data("amount");
  let selectedAmountOff = selected.data("amount-off");
  let selectedPercentOff = selected.data("percent-off");
  let selectedStr = selected.text();
  let amountOffMoney = (selectedAmountOff / 100).toFixed(2);

  if (selectedPercentOff > 0) {

    selectedAmount = (selectedAmount * (100 - selectedPercentOff) / 100).toFixed(2);

  } else if (selectedAmountOff > 0) {

    selectedAmount = (selectedAmount - amountOffMoney).toFixed(2);
    $("#plan-options option:selected").data("amount", selectedAmount);

    // Log updated amount that was set on data-amount attr
    console.log('updated data-amount value: ' + selected.data("amount"));

  } else {
    alert("Someting wrong happened!");
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="plan-options">
  <option value="">-Select-</option>
  <option value="" data-amount="15.00" data-amount-off="5.00" data-percent-off="">15.00</option>
</select>
<div id="selected-price"></div>