Why is the onclick event on the body element not w

2020-07-20 04:10发布

问题:

I'm trying to send users to another page when click html body:

JavaScript c.js:

function clickBody(){
    window.location.href = '/';
}

HTML:

<!DOCTYPE html>
<html>
<head>
    <script src="c.js"></script>
</head>

<body onclick="clickBody();">
</body>  
</html>

I can run the function from console, but clicking the <body> is not working.

回答1:

<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>


回答2:

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>