[英]JavaScript click event not working on div
我有兩個彩色 div,我想在上面放置事件。 我使用 getElementById 選擇了它們並且效果很好 - 當我 console.log 變量時,我得到了正確的 div。
但是,單擊事件似乎根本沒有觸發。 我基本上只是想檢查它是否與 console.log 一起工作,所以這就是函數返回的內容。
這是 HTML 代碼:
<html>
<head>
<style>
#red{
background: red;
width: 50px;
height: 50px;
}
#blue {
background-color: blue;
width: 50px;
height: 50px;
}
</style>
</head>
<body>
</div>
<div class="color picker">
<h2>Pick a color!</h2>
<div id="red"></div>
<div id="blue"></div>
<div id="green"></div>
</div>
</div>
</body>
<html>
這里是 JavaScript
var redColor = document.getElementById('red');
var blueColor = document.getElementById('blue');
function loadEventListeners(){
redColor.addEventListener('click', pickRed);
};
function pickRed(){
console.log("You have selected red");
}
感謝您的幫助!
您似乎還沒有調用loadEventListeners
。 這樣做應該可以解決問題。
您的 loadEventListeners 函數永遠不會被調用。 您可以在使用IIFE之后直接調用它
function pickRed(){ console.log("You have selected red"); } function loadEventListeners(){ document.getElementById('red').addEventListener('click', pickRed); }; loadEventListeners();
#red{ background: red; width: 50px; height: 50px; } #blue { background-color: blue; width: 50px; height: 50px; }
<html> <head> </head> <body> </div> <div class="color picker"> <h2>Pick a color!</h2> <div id="red"></div> <div id="blue"></div> <div id="green"></div> </div> </div> </body> <html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.