onclick事件绑定异常:点击文档任意区域触发,需仅响应#top元素
问题:onclick绑定到#top后,点击文档任意区域都会触发函数
问题描述
点击文档任意区域时,code()函数都会被触发;但使用HTML内联onclick事件时,仅点击#top元素才会执行对应逻辑。目标是让code()函数仅在点击#top元素时执行。
代码示例
JavaScript
top = document.querySelector("#top"); let topActive = false; top.onclick = code; function code () { console.log("This executes if I click anywhere on the document"); }
CSS
* { margin: 0; padding: 0; } body { width: 100%; min-height: 100vh; } .container { height: 100vh; display: grid; grid-template-rows: 1fr 1fr; grid-template-columns: 1fr; } #top { cursor: pointer; background-color: #5b6078; } #bottom { cursor: pointer; background-color: #24273a; }
HTML
<html> <head> <title>Audio</title> <link rel="stylesheet" href="index.css" /> </head> <body> <div class="container"> <div id="top" onclick="console.log('This executes only when I click #top')"></div> <div id="bottom"></div> </div> <script src="test.js"></script> </body> </html>
解决方案
问题出在变量名top上——top是浏览器全局对象window的内置属性(指向当前窗口的顶层窗口),你没有用let/const声明这个变量,导致它自动成为全局变量,覆盖了window.top。这时候你实际上是把onclick事件绑定到了window对象上,所以点击文档任何区域都会触发code()函数。
只需要给变量添加const或let声明,避免覆盖全局内置属性:
// 添加const声明变量,同时可以换个更清晰的变量名 const topElement = document.querySelector("#top"); let topActive = false; topElement.onclick = code; function code () { console.log("This executes only when I click #top"); }
或者用addEventListener绑定事件,效果一致:
const topElement = document.querySelector("#top"); let topActive = false; topElement.addEventListener('click', code); function code () { console.log("This executes only when I click #top"); }
修改后,点击#top区域才会在控制台输出日志,点击其他区域不会触发,和内联onclick的效果完全匹配。
内容的提问来源于stack exchange,提问作者shrubfromtomorrow
相关产品推荐
相关产品推荐

