温度切换按钮开发求助:点击后温度自动跳回原单位问题
Hey there! Let's break down what's probably causing your temperature toggle to flip right back, and fix it up step by step.
First off, the "switch to Fahrenheit then immediately back to Celsius" issue is super common—usually tied to event handling quirks or misusing jQuery's toggle() function (which you mentioned). Let's dive into the most likely fixes:
1. You're using jQuery's toggle() the old way (and it's broken)
Heads up: jQuery 1.9+ removed the event-switching version of
toggle(). The function now only handles showing/hiding elements, not alternating between two click behaviors. If you're still writing code like$('.toggle-btn').toggle(function(){/* switch to F */}, function(){/* switch to C */}), that's why your logic is failing.
Fix: Manually track the toggle state
Use a simple boolean variable to keep track of which unit is active, then run your conversion logic on each click:
// Initialize state: start with Celsius let isCelsius = true; // Store your current temperature value (update this as needed) let currentTemp = 22; // Handle button clicks $('.temp-toggle-btn').on('click', function(e) { // Prevent any accidental default behavior (like form submission) e.preventDefault(); flipTemperatureUnit(); }); // Handle temperature symbol clicks $('.temp-unit').on('click', function(e) { e.preventDefault(); flipTemperatureUnit(); }); // Core toggle logic function flipTemperatureUnit() { isCelsius = !isCelsius; if (isCelsius) { // Convert back to Celsius and update UI currentTemp = Math.round((currentTemp - 32) * 5/9); $('.temp-value').text(currentTemp); $('.temp-unit').text('°C'); } else { // Convert to Fahrenheit and update UI currentTemp = Math.round(currentTemp * 9/5 + 32); $('.temp-value').text(currentTemp); $('.temp-unit').text('°F'); } }
2. Event bubbling is triggering two toggles at once
If your button and temperature symbol are nested (or share a parent element), clicking one might trigger both their click events. That means you're switching to Fahrenheit, then immediately switching back in the same click.
Fix: Stop event propagation
Add e.stopPropagation() to your click handlers to prevent the event from bubbling up to parent elements:
$('.temp-toggle-btn').on('click', function(e) { e.preventDefault(); e.stopPropagation(); // Stop the event from spreading flipTemperatureUnit(); }); $('.temp-unit').on('click', function(e) { e.preventDefault(); e.stopPropagation(); flipTemperatureUnit(); });
3. Your button is triggering a form submission
If your toggle button is inside a <form> tag, it might be defaulting to submitting the form—refreshing the page and resetting your temperature display instantly.
Fix: Block form submission
Either add e.preventDefault() to the button click (as above), or block the form's default behavior directly:
$('form').on('submit', function(e) { e.preventDefault(); // Stop the form from reloading the page });
内容的提问来源于stack exchange,提问作者mso4491

