亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將(格式良好的)字符串變量分配給 <input type="date" /> 值

如何將(格式良好的)字符串變量分配給 <input type="date" /> 值

RISEBY 2021-08-20 16:21:30
我正在嘗試將表示日期的格式良好的字符串變量 (yyyy-mm-dd) 分配給<input type="date" />. 當值是字符串文字時,它起作用,但是當它來自變量或常量時,它不起作用。您可以檢查以下 html 代碼和呈現的 html 頁面。<form>  <p>Litteral Assignement: <input name="literalDate" type="date" /></p>  <p>Variable Assignement: <input name="variableDate" type="date" /></p></form><script>  var literalDateControl = document.querySelector('input[name="literalDate"]');  literalDateControl.value = "2019-07-24";  var today = new Date();  const todayValue = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();  var variableDateControl = document.querySelector('input[name="variableDate"]');  variableDateControl.value = todayValue;</script>關于如何解決這個問題的任何想法或建議?
查看完整描述

3 回答

?
拉莫斯之舞

TA貢獻1820條經驗 獲得超10個贊

問題是你的月份不是兩位數。有很多方法可以填充單個數字,但它可能看起來像這樣:


const getMonth = date => `${date.getMonth() + 1 < 10 ? '0' : ''}${date.getMonth() + 1}`;


const today = new Date();

const todayTest = today.getFullYear() + '-' + getMonth(today) + '-' + today.getDate();


const fixedTest = "2019-07-24";


document.querySelector('.a').value = todayTest;

document.querySelector('.b').value = fixedTest;


console.log(todayTest)

console.log(fixedTest)

<input class="a" type="date" />

<input class="b" type="date" />


查看完整回答
反對 回復 2021-08-20
  • 3 回答
  • 0 關注
  • 187 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號