【问题标题】:Onclick Event Targeting Whole Document针对整个文档的 Onclick 事件
【发布时间】:2022-10-13 11:58:44
【问题描述】:

当我单击文档上的任意位置时,我的 onclick 事件正在触发。

如果我在 HTML 中创建内联 onclick 事件,则 onclick 会按预期工作。

我的目标是让 code() 仅在我单击 #top 元素时执行。

top = document.querySelector("#top");
let topActive = false;
top.onclick = code;
function code () {
    console.log("This executes if I click anywhere on the document");
}
* {
    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>
    <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>

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    在顶层,top 已经作为标识符存在——它指的是window.top,它指向顶层窗口(除非你已经在处理 iframe,这就是窗口本身)。所以当你这样做时

    top = document.querySelector("#top");
    

    它静默失败,因为window.top 不可重新分配。 (考虑改用严格模式;它会将静默失败转变为更容易调试的显式错误。)

    然后当你这样做

    top.onclick = code;
    

    因为topwindow.top 相同,而window.top 只是窗口(大多数情况下),上面相当于

    window.onclick = code;
    

    因此,对窗口的任何点击都会运行处理程序。

    使用不同的变量名,或在 IIFE 中运行代码(并确保将来使用 constletvar 声明您的变量)。

    const topDiv = document.querySelector("#top");
    let topActive = false;
    topDiv.onclick = code;
    
    function code() {
      console.log("OK now");
    }
    * {
      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;
    }
    <div class="container">
      <div id="top" onclick="console.log('This executes only when I click #top')"></div>
      <div id="bottom"></div>
    </div>

    【讨论】:

      【解决方案2】:

      需要在onclick=""中调用top函数

      【讨论】:

        猜你喜欢
        • 2021-05-06
        • 2016-08-07
        • 2019-08-04
        • 1970-01-01
        • 1970-01-01
        • 2019-06-06
        • 1970-01-01
        • 2012-02-18
        • 2014-12-13
        相关资源
        最近更新 更多