Displaying clock in div with javascript

2019-06-09 20:45发布

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条回答
在下西门庆
2楼-- · 2019-06-09 21:11

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

查看更多
登录 后发表回答