Why is the onclick event on the body element not working?

前提是你 提交于 2019-12-04 16:29:35
Shijin

<body> element have no height, add something like bellow:

<!DOCTYPE html>
<html>
<head>
  <style>
    body {
     height: 500px;
    }
  </style>
  <script src="c.js"></script>
</head>

<body onclick="clickBody();">

</body>  
</html>
Michał Perłakowski

The <body> element is empty. You have to either change its height in CSS, or put some text in it.

Also, using element.addEventListener() might be a good idea. See addEventListener vs onclick.

See code snippet:

function clickBody() {
    window.location.href = '/'
}
document.body.addEventListener("click", clickBody)
<!DOCTYPE html>
<html>
<head>
    <script src="c.js"></script>
</head>

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