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

如何实现选择input type="date"日期时动态更新<p>元素?

解决日期选择后动态更新

元素的问题

你的代码里存在一个变量名拼写错误,这是导致<p>元素无法更新的核心原因:

在change事件监听函数中,你定义了变量selectedDate1,但赋值给test3.textContent时误用了未定义的selectedDate,这会触发ReferenceError,导致代码执行中断。

修正后的完整代码

<div><h4 style="padding: 5px">Select a date</h4></div>
<input type="date" id="datepicker" name="date" required />
<script>
var currentDate = new Date().toISOString().split("T")[0];
document.getElementById("datepicker").min = currentDate;
</script>
<p id="testVariable1"></p>
<p id="testVariable2"></p>
<p id="testVariable3"></p>
<div><input type="submit" value="Submit" class="btn btn-primary" /></div>
<script>
const hotdeskLinks = document.querySelectorAll(".test a");
var allBookings = "{{all-bookings}}";
var decodedBookings = allBookings.replace(/&quot;/g, '"');
// 优化:避免重复解析JSON,提升性能
const parsedBookings = JSON.parse(decodedBookings);

const test1 = document.getElementById("testVariable1");
const workspaceAttributes = parsedBookings.map(item => item.workspace);
test1.textContent = workspaceAttributes;

const test2 = document.getElementById("testVariable2");
const dateAttributes = parsedBookings.map(item => item.date);
test2.textContent = dateAttributes;

const datepicker = document.getElementById("datepicker");
const test3 = document.getElementById("testVariable3");
datepicker.addEventListener("change", function (event) {
  // 修正变量名,或直接使用event.target.value更贴合事件逻辑
  test3.textContent = event.target.value;
});
</script>

额外优化说明

  1. 避免重复解析JSON:将JSON.parse(decodedBookings)的结果存储为变量,避免两次解析同一字符串,提升代码性能。
  2. 使用event.target.value:在事件回调中直接通过事件对象获取目标元素的值,逻辑更清晰,也避免依赖外部变量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 12:35:34