使用 javascript 在 div 中显示时间 am/pm [英] display time am/pm inside a div with javascript

查看:74
本文介绍了使用 javascript 在 div 中显示时间 am/pm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,如果之前有人回答过这个问题,我很抱歉,但我一直没能找到解决办法.我对 js 完全陌生,所以请保持友善 :)

Hi Everyone I am sorry if this question has been answered before but I haven't been able to find a solution. I am completely new to js so please be nice :)

我想问一下如何在div中显示时间?我无法在我的页面上显示此功能.当我在浏览器中启动页面时,它只是空白.

I wanted to ask how can I have the time display inside a div? I can't get this function to display on my page. When I launch the page in the browser, it is just blank.

谢谢,我希望我的问题有意义.

Thank you, I hope my question makes sense.

document.getElementById("para1").innerHTML = formatAMPM(date);

function formatAMPM(date) {
  var elem = document.getElementById("para1");
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ' ' + ampm;
  return strTime;
 }

推荐答案

你需要这个:

document.getElementById("para1").innerHTML = formatAMPM(new Date());

而且您可能还想将其包装在类似 jQuery 的 ready() 中以确保 DOM 已加载:

And you might also want to wrap it in something like jQuery's ready() to make sure the DOM has been loaded:

$(document).ready(function() {
    // Handler for .ready() called.
});

http://api.jquery.com/ready/

jQuery 不是唯一的方法,而只是一个建议.

jQuery's isn't the only way, but just a suggestion.

这篇关于使用 javascript 在 div 中显示时间 am/pm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆