[英]Concatenate the date in each element
I want to concatenate the dates. 我想连接日期。 This is my codes, I created first the year today and next date that I add 1 month to become 2019. I don't know what the problem is why it didn't display the result.
这是我的代码,我今天首先创建了第一年,第二天又添加了一个月,直到2019年。我不知道是什么问题,为什么它没有显示结果。
function myFunction() { var d = new Date(); var n = d.getFullYear(); var date = document.getElementById("demo").innerHTML = n; var d1 = new Date(); var n1 = d1.getFullYear()+1; var date1 = document.getElementById("demo1").innerHTML = n1; var str3 = "-"; var res = date.concat(str3,date1); document.getElementById("disp").innerHTML = res; }
<!DOCTYPE html> <html> <body onload="myFunction()"> <p>Click the button to display the full year of todays date.</p> <p id="demo"></p> <p id="demo1"></p> <p id="disp"></p> </body> </html>
date
is a number. date
是一个数字。 Number
does not have concat
function. Number
不具有concat
功能。 Convert it into a string. 将其转换为字符串。
function myFunction() { var d = new Date(); var n = d.getFullYear(); var date = document.getElementById("demo").innerHTML = n+""; // convert to string var d1 = new Date(); var n1 = d1.getFullYear()+1; var date1 = document.getElementById("demo1").innerHTML = n1+""; var str3 = "-"; var res = date.concat(str3,date1); document.getElementById("disp").innerHTML = res; }
<!DOCTYPE html> <html> <body onload="myFunction()"> <p>Click the button to display the full year of todays date.</p> <p id="demo"></p> <p id="demo1"></p> <p id="disp"></p> </body> </html>
I don't know what the problem is why it didn't display the result.
我不知道问题是什么,为什么它不显示结果。
Because you are getting 因为你越来越
"Uncaught TypeError: date.concat is not a function",
“未捕获的TypeError:date.concat不是函数”,
date
is a number , it doesn't have concat method. date
是一个数字 ,没有concat方法。 Convert it to String
first. 首先将其转换为
String
。
var res = String(date).concat(str3,date1);
Demo 演示版
function myFunction() { var d = new Date(); var n = d.getFullYear(); var date = document.getElementById("demo").innerHTML = n; var d1 = new Date(); var n1 = d1.getFullYear()+1; var date1 = document.getElementById("demo1").innerHTML = n1; console.log(date, date1); var str3 = "-"; var res = String(date).concat(str3,date1); document.getElementById("disp").innerHTML = res; }
<!DOCTYPE html> <html> <body onload="myFunction()"> <p>Click the button to display the full year of todays date.</p> <p id="demo"></p> <p id="demo1"></p> <p id="disp"></p> </body> </html>
String.prototype.concat() String.prototype.concat()
It is strongly recommended to use the string concatenation operators (+, +=) instead of this method for perfomance reasons
出于性能原因,强烈建议使用字符串连接运算符(+,+ =)代替此方法
var res = date + str3 + date1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.