在URL中为特定日期模式动态创建HTML链接

qij5mzcb  于 2022-11-27  发布在  其他
关注(0)|答案(2)|浏览(173)

我需要创建一个动态链接来超链接一个字符串,这样任何人点击该字符串都会打开与当天相关的链接。例如,如果有人点击今天,就会打开此链接。https://sobbanglay.com/sob/history-today-november-23/
你能帮我创建一个简单的脚本来动态创建上面的URL模式吗?
我尝试了下面这样的东西,从这个论坛的帮助,但我不能打印字符串的月份。你能帮我实现这是与简单的html脚本像下面?

<a href="https://sobbanglay.com/sob/history-today-january-01/" id="link">As it happened on today</a>

<script>
var d = new Date();
var month = d.getMonth() +1;

var day = d.getDate();

document.getElementById("link").href = "https://sobbanglay.com/sob/history-today-" + month + "-" + day + "/";
</script>
oknwwptz

oknwwptz1#

正如你所看到的,如果你按下链接,你会得到月份(11),但如果你想十一月,你可以尝试使一个开关的情况下(只是使所有的情况)

<a href="https://sobbanglay.com/sob/history-today-january-01/" id="link">As it happened on today</a><script>
var monthNames = ["January","February","March","April","May","June","July","August","September","October","November","December"];


var d = new Date();
let month = monthNames[d.getMonth()];
var day = d.getDate();


document.getElementById("link").href = "https://sobbanglay.com/sob/history-today-" + month + "-" + day + "/";
</script>

我知道这不是最好的答案,但它确实有效。

uklbhaso

uklbhaso2#

<script> 
const months = ["January", "February", "March", "April", "May", "June", "July","August", "September", "October", "November", "December"];
const days= ["Sun","Mon", "Tue","Wed","Thurs","Fri","Sat"];
var d = new Date();
var month = d.getMonth();
var day = d.getDay();
var year=d.getFullYear();
document.getElementById("link").href=`https://sobbanglay.com/sob/history-${days[month]}-${months[month]}-${year}`;
</script>

相关问题