我已经得到了一些JavaScript,它可以创建一个数字时钟,并将其放入网页。这是完美的工作,但是,我正在尝试修改它,以包装在span或粗体标记的am/pm后缀(或在此代码中的Diem ),以便我可以在CSS中的其余时间不同的样式。
我相信对于知道自己在做什么的人来说,这真的很简单,但我真的很挣扎。
任何帮助都将不胜感激,JavaScript如下所示:
function renderTime() {
var currentTime = new Date();
var diem = "AM";
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
setTimeout('renderTime()',1000);
if (h == 0) {
h = 12;
} else if (h > 12) {
h = h - 12;
diem="PM";
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
var myClock = document.getElementById('clockDisplay');
myClock.textContent = h + ":" + m + " " + diem;
myClock.innerText = h + ":" + m + " " + diem;
var diem = document.createElement('span');
}
renderTime();所以,我想做同样的事情,但是使用URL样式,就像这样:http://example.com/example?h="10"&m="42"
发布于 2020-12-17 06:53:15
只需将小时和分钟连接到URL前缀,并将其作为字符串返回。
此外,您的代码为中午到12:59之间的时间生成了错误的时间,因为这些时间应该是12点。
function getTimeURL() {
var currentTime = new Date();
var diem = "AM";
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
if (h == 0) {
h = 12;
} else if (h > 12) {
h = h - 12;
diem="PM";
} else {
diem = "PM";
}
if (m < 10) {
m = "0" + m;
}
var url = `http://example.com/example?h=${h}${diem}&m=${m}`;
return url;
}
console.log(getTimeURL());
发布于 2020-12-17 08:34:58
我给你的代码添加了一堆注释,希望能让你的代码更容易理解。我还添加了一个全局变量,当函数更改linkText值时,它将存储该值。
// create a global variable that stores our text for the link.
// Your renderTime() function will update it every second.
var linkText = "";
function renderTime() {
//grab the new date
var currentTime = new Date();
//set diem (whatever that means) to "AM"
var diem = "AM";
//get the hours from our current time
var h = currentTime.getHours();
//get the minutes
var m = currentTime.getMinutes();
//get the seconds
var s = currentTime.getSeconds();
//run this function every 1000 milliseconds
setTimeout('renderTime()', 1000);
//if the hour is 0, set it to twelve instead
if (h == 0) {
h = 12;
//else if the hour is any number higher than 12,
//subtract 12 from its value and change diem to "PM"
} else if (h > 12) {
h = h - 12;
diem = "PM";
}
//if the minutes are 0-9 add a 0 before.
if (m < 10) {
m = "0" + m;
}
//if the seconds are 0-9 add a 0 before.
if (s < 10) {
s = "0" + s;
}
//get our clock element
var myClock = document.getElementById('clockDisplay');
//populate our clock element
myClock.textContent = h + ":" + m + ":" + s + " " + diem;
myClock.innerText = h + ":" + m + ":" + s + " " + diem;
//not sure why you're writing over your AM/PM variable at the end here,
//so I commented it out
//var diem = document.createElement('span');
//set our linkText value to be the current hour and minute
linkText = 'http://example.com/example?h="' + h + '"&m="' + m + '"';
}
//run that thang!
renderTime();<div id="clockDisplay"></div>
https://stackoverflow.com/questions/65332188
复制相似问题