簡體   English   中英

addEventListener 中的 Function 不起作用

[英]Function inside addEventListener doesn't work

const bubbles = document.querySelectorAll('.bubble')

function filledBubble (event){
    event.classList.toggle("filled");
}

bubbles.forEach((bubble) => {
    bubble.addEventListener('click', filledBubble);
})

大家好,

我試圖將一個事件應用於我的氣泡。 所以當我們點擊時,它會改變顏色。 但不知何故,我不知道為什么我的 function 不起作用。 此外,在控制台上,它也沒有顯示語法錯誤。

您在我的代碼中看到任何錯誤嗎?

HTML 代碼

<h3>Select</h3>
    <div class="container">
        <div class="bubble"></div>
        <div class="bubble"></div>
        <div class="bubble"></div>
    </div>

使用event.target event.target.classList.toggle("filled")
或者這個this.classList.toggle("filled")

演示:

 const bubbles = document.querySelectorAll('.bubble') function filledBubble (event){ this.classList.toggle("filled"); } bubbles.forEach((bubble) => { bubble.addEventListener('click', filledBubble); })
 .bubble { margin: .5em; cursor: pointer; }.filled { background-color: green; }
 <h3>Select</h3> <div class="container"> <div class="bubble"> bubble 1</div> <div class="bubble"> bubble 2</div> <div class="bubble"> bubble 3</div> </div>

正如其他人所提到的, event.target.classList.toggle("filled")是答案,但既然你說它不是那么你有 javascript 初始化發生在 HTML 已經呈現之前。 換句話說,將 javascript 放在 HTML 之后。

或者,在頁面加載后運行 javascript 初始化:

<head>
<script>

let bubbles

function initJS() {
  bubbles = document.querySelectorAll('.bubble');
  bubbles.forEach((bubble) => {
    bubble.addEventListener('click', filledBubble);
  });
}

function filledBubble (event){
  this.classList.toggle("filled");
}

</script>
</head>
<body onload='initJS()'>
...
<h3>Select</h3>
<div class="container">
    <div class="bubble"> bubble 1</div>
    <div class="bubble"> bubble 2</div>
    <div class="bubble"> bubble 3</div>
 
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM