Javascript 为什么 body 元素上的 onclick 事件不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37075058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is the onclick event on the body element not working?
提问by user1234597
I'm trying to send users to another page when click html body:
单击 html body 时,我试图将用户发送到另一个页面:
JavaScript c.js
:
JavaScript c.js
:
function clickBody(){
window.location.href = '/';
}
HTML:
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.
我可以从控制台运行该功能,但单击<body>
不起作用。
回答by Micha? Per?akowski
The <body>
element is empty. You have to either change its height in CSS, or put some text in it.
该<body>
元素为空。您必须在 CSS 中更改其高度,或者在其中放置一些文本。
Also, using element.addEventListener()
might be a good idea. See addEventListener vs onclick.
此外,使用element.addEventListener()
可能是一个好主意。请参阅addEventListener 与 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>
回答by Shijin TR
<body>
element have no height, add something like bellow:
<body>
元素没有高度,添加如下内容:
<!DOCTYPE html>
<html>
<head>
<style>
body {
height: 500px;
}
</style>
<script src="c.js"></script>
</head>
<body onclick="clickBody();">
</body>
</html>