You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现折扣的应用与移除?含动态价格与15%折扣复选框需求

Dynamic Price Discount with Checkbox Solution

Got it, let's get your dynamic price discount feature working correctly! Your core idea is spot-on—add a checkbox that applies a 15% discount when checked, and reverts to the original price when unchecked—but there's a small flaw in your current code that will break the "revert to original price" functionality. Let's fix that up.

The Problem with Your Current Code

When you first run var value = $('p').text(), you grab the original price. But after checking the checkbox, the <p> tag's text gets updated to the discounted price. If you then uncheck the box, your code will set the <p> tag to that discounted value (not the original price), so you'll lose the original price forever.

Fixed Solution

First, let's set up the full HTML structure (since it's missing from your snippet), then the corrected jQuery code:

HTML

<!-- Display the original price here -->
<p id="price" data-original-price="100">100</p>

<!-- Discount checkbox -->
<label>
  <input type="checkbox" id="discount"> Apply 15% Discount
</label>

<!-- Load jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Corrected jQuery Code

$(document).ready(function() {
  // Store the original price once (we use the data attribute for persistence)
  const originalPrice = parseInt($('#price').data('original-price'));

  $('#discount').click(function() {
    if ($(this).is(':checked')) {
      // Calculate 15% discount
      const discountedPrice = originalPrice - (originalPrice * 0.15);
      $('#price').text(discountedPrice);
    } else {
      // Revert to original price
      $('#price').text(originalPrice);
    }
  });
});

Key Improvements

  • Persist the Original Price: We store the original price in a data-original-price attribute on the <p> tag, so we always have access to it—no matter how many times the checkbox is toggled.
  • Cleaner Logic: We use $(this) instead of re-selecting #discount inside the click handler, which is more efficient.
  • Decimal Handling (Optional): If you need to handle prices with decimals, replace parseInt with parseFloat and use .toFixed(2) to keep two decimal places (e.g., discountedPrice.toFixed(2)).

How It Works

  1. When the page loads, we grab the original price from the data-original-price attribute and store it in a constant.
  2. When the checkbox is clicked:
    • If checked: Calculate the discounted price (original price minus 15% of the original) and update the <p> tag.
    • If unchecked: Set the <p> tag back to the original price we stored earlier.

内容的提问来源于stack exchange,提问作者Tom Bom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:39:49