JS实现将日期选择器中month类span的数字月份转3字符缩写
Hey there! Since you're already working with jQuery and have the two-digit month format sorted out, let's walk through how to use an array to convert those numbers to 3-character uppercase abbreviations (like JAN, FEB) for your .month span elements. This is super approachable for JS beginners—let's dive in!
Step 1: Create a Month Abbreviation Array
First, we'll make an array where the index number matches the month number (since your two-digit months are 01-12, which convert to integers 1-12). We'll leave the 0th index empty so we don't have to do extra math later:
// Index 1 = January (JAN), Index 2 = February (FEB), etc. const monthAbbrs = ['', 'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
Step 2: Target & Update Your .month Spans
Next, we'll use jQuery to find all .month spans, loop through each one, and replace the two-digit number with the corresponding abbreviation:
// Loop through every .month span on the page $('.month').each(function() { // Get the two-digit month text (trim removes any extra spaces) const twoDigitMonth = $(this).text().trim(); // Convert the two-digit string to an integer (e.g., "01" → 1, "12" → 12) // Adding ", 10" ensures we use decimal numbering (avoids weird octal bugs) const monthNumber = parseInt(twoDigitMonth, 10); // Grab the abbreviation from our array; if the month number is invalid, keep the original text const monthAbbreviation = monthAbbrs[monthNumber] || twoDigitMonth; // Replace the span's text with the abbreviation $(this).text(monthAbbreviation); });
Key Notes for Beginners
- Why the empty first array item? Since your months are 01-12 (which become integers 1-12), using index 1 for January means we don't have to subtract 1 from the month number—no extra steps to mess up!
parseInt(twoDigitMonth, 10): Always include the second parameter (10) to make sure JS interprets the number as base-10 (decimal), not octal (which can happen with numbers starting with 0 in older JS versions).- Fallback for invalid months: The
|| twoDigitMonthpart ensures if someone enters a bad value (like "13"), the original text stays instead of showingundefined.
When to Run This Code
Make sure you run this after your date picker has populated the .month spans. You can either:
- Put it inside the date picker's callback function (the code that runs after a date is selected)
- Wrap it in
$(document).ready()if the spans are already present when the page loads
内容的提问来源于stack exchange,提问作者z3r0

