Displaying clock in div with javascript

自闭症网瘾萝莉.ら 提交于 2019-12-10 11:56:32

问题


I'm getting grey haired here because I can't get this clock to display on my SPA. I'm haveing a clock that should be displayed on the page but I can't seem to get it right. I have tried the things we were taught at the course but I can't seem to get it right. Could you please take a look at it and lend a hand perhaps. Not even the console.log is printed out.

Code in Clock.js:

function clock () {
  let now = new Date()
  let h = now.getHours()
  let m = now.getMinutes()
  let s = now.getSeconds()

  m = checkTime(m)
  s = checkTime(s)

  let target = document.querySelector('#footer-clock')
  let clockText = document.createTextNode(h + ':' + m + ':' + s)
  target.appendChild(clockText)

  setInterval(clock, 500)
}

function checkTime (i) {
  if (i < 10) {
    i = '0' + i
  }
  return i
}

module.exports = clock

Code in app.js:

const clock = require('./clock.js')

document.querySelector('#footer-clock').onload = function () {
  clock()
  console.log('Loaded')
}

And in HTML I have:

footer>
  <div id="footer-clock">

  </div>
</footer>

回答1:


The browser doesn't understand what

module.exports = {}
const clock = require('./clock.js')

this will work when you use something like webpack for bundling and using commonjs Module also if you look at the console in devtools in chrome you will see this error

Uncaught ReferenceError: require is not defined

note that : when you developing sites using html you should put any scripts in the script tag like this

<script src="app.js"></script>
<script src="clock.js"></script>

now the code in clock.js will be available any where so in app.js you can call the method without require function

clock()

also you need to use window.onload instead of

document.querySelector('#footer-clock').onload = function () {
clock()
console.log('Loaded')
}

here you can learn more about global events



来源:https://stackoverflow.com/questions/47930156/displaying-clock-in-div-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!