如何实现折扣的应用与移除?含动态价格与15%折扣复选框需求
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-priceattribute 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#discountinside the click handler, which is more efficient. - Decimal Handling (Optional): If you need to handle prices with decimals, replace
parseIntwithparseFloatand use.toFixed(2)to keep two decimal places (e.g.,discountedPrice.toFixed(2)).
How It Works
- When the page loads, we grab the original price from the
data-original-priceattribute and store it in a constant. - 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.
- If checked: Calculate the discounted price (original price minus 15% of the original) and update the
内容的提问来源于stack exchange,提问作者Tom Bom

