HTML传值至JavaScript时字符串值异常:日期显示错误求助
问题原因与解决方案
问题根源
点击按钮后日期显示错误,是因为调用edit函数时,{{ note.date }}没有用引号包裹。JavaScript会把类似06-24-2024的日期字符串当作减法表达式计算,最终得到错误的数字结果。
修复步骤
- 修正按钮的onclick参数传递
找到未锁定记录对应的按钮代码,给{{ note.date }}添加单引号,让JavaScript将其识别为字符串类型:
<!-- 修改前 --> <button type="button" onclick="edit({{ note.id }},{{ note.date }},{{ note.mins }},{{ note.hours }})" style="background-color:grey;border: 2px solid grey;"> <!-- 修改后 --> <button type="button" onclick="edit({{ note.id }}, '{{ note.date }}', {{ note.mins }}, {{ note.hours }})" style="background-color:grey;border: 2px solid grey;">
- 可选优化:规范日期输入框类型
底部的editday输入框当前为text类型,若需要支持系统日期选择器,可将其改为date类型,但需确保后端返回的note.date格式为YYYY-MM-DD(HTML标准日期格式):
<!-- 修改前 --> <input type="text" name="editday" id="editday" value=""> <!-- 修改后 --> <input type="date" name="editday" id="editday" value="">
内容的提问来源于stack exchange,提问作者Demi Hudson
相关产品推荐
相关产品推荐

