當我單擊檔案上的任意位置時,我的 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>
uj5u.com熱心網友回復:
在頂層,top已經作為識別符號存在 - 它指的是window.top,它指向頂層視窗(除非您已經在處理 iframe,否則這是視窗本身)。所以當你這樣做時
top = document.querySelector("#top");
它默默地失敗,因為window.top不可重新分配。(考慮改用嚴格模式;它會將靜默失敗轉變為更容易除錯的顯式錯誤。)
然后當你這樣做
top.onclick = code;
因為top與 , 相同window.top,并且window.top只是視窗(在大多數情況下),所以上面等價于
window.onclick = code;
因此,對視窗的任何點擊都會運行處理程式。
使用不同的變數名,或在 IIFE 中運行代碼(并確保在將來使用constorlet或 or宣告您的變數var)。
顯示代碼片段
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>
uj5u.com熱心網友回復:
需要在 onlick="" 中呼叫 top 函式
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/511116.html
