如何使用JavaScript将输入框日期转为DDMMYYYY以更新图片src
解决方案
要将日期格式从YYYYMMDD改为DDMMYYYY拼接图片路径,只需修改表单提交事件中处理日期格式的逻辑,具体步骤如下:
- 拆分用户选择的日期字符串(格式为
YYYY-MM-DD),提取年、月、日三个部分 - 按
日+月+年的顺序重新拼接成DDMMYYYY格式的字符串 - 使用格式化后的日期替换原代码中直接去除横杠的日期值
修改后的完整代码如下:
<center><span>-: Select Your City :-</span><br> <form action="" method="POST"> <select name="city"> <option value="">Select city...</option> <option value="de" selected>Delhi</option> <option value="mu">Mumbai</option> <option value="lc">Lucknow</option> </select> <br><br> <span>-: Select Date :-</span> <br> <input type="date" name="old" value="2023-01-13" min="2021-01-01" max="2023-01-13" required /> <br><br> <input type="submit" value="Go" /> </form> </center> <img src="https://image.example.com/images/13012023/13012023-de-1.jpg"><br> <img src="https://image.example.com/images/13012023/13012023-de-2.jpg"><br> <img src="https://image.example.com/images/13012023/13012023-de-3.jpg"><br> <img src="https://image.example.com/images/13012023/13012023-de-4.jpg"><br> <img src="https://image.example.com/images/13012023/13012023-de-5.jpg"><br> <script> const today = new Date(); const year = today.getFullYear(); const month = String(today.getMonth() + 1).padStart(2, '0'); const day = String(today.getDate()).padStart(2, '0'); // Get the form elements const form = document.querySelector('form'); const citySelect = form.querySelector('select[name="city"]'); const dateInput = document.querySelector('input[type="date"]'); dateInput.value = `${year}-${month}-${day}`; dateInput.max = `${year}-${month}-${day}`; // Get all the img elements const images = document.querySelectorAll('img'); // Add an event listener to the form that will run a function // when the form is submitted form.addEventListener('submit', (event) => { // Prevent the form from submitting and refreshing the page event.preventDefault(); // Get the selected city and date values const city = citySelect.value; const date = dateInput.value; // 转换日期格式为DDMMYYYY const [dateYear, dateMonth, dateDay] = date.split('-'); const formattedDate = dateDay + dateMonth + dateYear; // Update the src attribute of each img element images.forEach((image, index) => { const imageNumber = String(index + 1); image.src = `https://image.example.com/images/${formattedDate}/${formattedDate}-${city}-${imageNumber}.jpg`; }); }); </script>
关键修改说明
- 新增日期拆分与格式化逻辑:通过
split('-')拆分日期字符串,再按日+月+年顺序拼接成目标格式 - 替换原代码中两处
date.replace(/-/g, '')为formattedDate,确保图片路径使用DDMMYYYY格式的日期
内容的提问来源于stack exchange,提问作者Dhiraz Singh
相关产品推荐
相关产品推荐

