簡體   English   中英

循環如何與 JavaScript EventListner 一起工作

[英]How for loop work with JavaScript EventListner

我有一個 html 文檔,其中有 3 個按鈕和一個 h1 元素。 我試圖通過單擊EventListene r 的每個按鈕來更改 h1 元素內容。 我也這樣做了。 但我不明白foo 循環如何在那里工作。 當我點擊它們時,按鈕的工作原理如何?

 //JavaScript Code var len = document.querySelectorAll(".mybutton").length for (let i = 0; i < len; i++) { var doucemnts = document.querySelectorAll("button")[i] doucemnts.addEventListener("click", function(){ var text = this.innerHTML document.querySelector("h1").innerHTML= "You Have Selected " + text console.log(i) }) }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Document</title> </head> <body> <h1>You have selected no button</h1> <button class="mybutton">Button 1</button> <button class="mybutton">Button 2</button> <button class="mybutton">Button 3</button> <script src="index.js"> </script> </body> </html>

誰能告訴我 For 循環是如何在那里工作的?

在 JS 中操作 DOM 元素時,最好在代碼開始時查詢元素一次,然后重用這些變量。 另一個需要考慮的重要事情是使用const / let代替舊的var關鍵字。 這是基於此的更新代碼,現在可能更有意義:

 const h1 = document.querySelector('h1'); const buttons = document.querySelectorAll('.mybutton'); for (let i = 0; i < buttons.length; i++) { buttons[i].addEventListener("click", function() { const text = this.innerHTML; h1.innerHTML = "You Have Selected " + text; }); }

這段代碼基本上是做同樣的事情,但不是在每次迭代中查詢元素,而是在開始循環之前完成一次。 然后逐個循環按鈕並為每個按鈕添加點擊事件。

您也可以使用for..of它可能更容易理解。 這是更新后用於for..of的代碼:

 const h1 = document.querySelector('h1'); const buttons = document.querySelectorAll('.mybutton'); for (const button of buttons) { button.addEventListener('click', function() { const text = this.innerHTML; h1.innerHTML = 'You Have Selected ' + text; }); }

更新:在這兩個代碼片段中要理解的主要內容是const text = this.innerHTML 這行代碼就是使用this關鍵字來獲取每個按鈕的 HTML 內容。 this關鍵字將指向觸發事件的按鈕,因此基於此,您將使用innerHTML屬性在該按鈕上顯示文本並將其連接到 h1 的內容。 簡而言之,將單擊按鈕中的文本和 append 獲取到 h1 內容。

我已經刪除了console.log(i)因為它引用了僅在添加事件偵聽器回調時才有效的變量i 它會顯示一個錯誤,因為當事件回調 function 被調用時,將沒有 for 循環並且我不會被定義。

節點列表中附加一個事件偵聽器,該偵聽器在單擊按鈕時調用 function。 function 使用按鈕文本更新h1

通過預先緩存所有元素,然后在循環中使用這些引用(for/of 循環更容易解析),可以稍微改進您的代碼。

 // Cache the elements const buttons = document.querySelectorAll('.mybutton'); const heading = document.querySelector('h1'); // Loop over `buttons` for (const button of buttons) { // For every button add a click listener button.addEventListener('click', function() { // Assign the button textContent to a new variable const text = this.textContent; // Use that variable to update the textContent // of the heading textContent heading.textContent = 'You Have Selected ' + text; }); }
 <h1>You Have Selected No Button</h1> <button class="mybutton">Button 1</button> <button class="mybutton">Button 2</button> <button class="mybutton">Button 3</button>

您甚至可以使用事件委托 它將一個偵聽器附加到父元素,當子元素“冒泡”DOM 時,它會從其子元素中捕獲事件。

 // Cache the elements, and a partial string const heading = document.querySelector('h1'); const buttons = document.querySelector('.buttons'); const tmpl = 'You Have Selected'; // Add an event listener to the buttons container buttons.addEventListener('click', handleClick); function handleClick(e) { // If the child element that fired the // click event is a button if (e.target.matches('button')) { // Construct the new string, and assign it // to the heading textContent const text = `${tmpl} ${e.target.textContent}`; heading.textContent = text; } }
 <h1>You Have Selected No Button</h1> <section class="buttons"> <button>Button 1</button> <button>Button 2</button> <button>Button 3</button> </section>

附加信息

暫無
暫無

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

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