简体   繁体   English

循环如何与 JavaScript EventListner 一起工作

[英]How for loop work with JavaScript EventListner

I have a html document where has 3 button and one h1 element.我有一个 html 文档,其中有 3 个按钮和一个 h1 元素。 I have tried to change the h1 element content by clicking in each button with EventListene r.我试图通过单击EventListene r 的每个按钮来更改 h1 元素内容。 And i have done this too.我也这样做了。 But i dont understand how foor loop work there.但我不明白foo 循环如何在那里工作。 How exact button working when i am click on them?当我点击它们时,按钮的工作原理如何?

 //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>

Can Anyone Tell me How For loop worked there?谁能告诉我 For 循环是如何在那里工作的?

In JS when manipulating DOM elements, it's better to query elements once at start of your code then reuse those variables.在 JS 中操作 DOM 元素时,最好在代码开始时查询元素一次,然后重用这些变量。 Another important thing to consider is to use const / let instead of old var keyword.另一个需要考虑的重要事情是使用const / let代替旧的var关键字。 Here's your updated code based on that and might make more sense now:这是基于此的更新代码,现在可能更有意义:

 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; }); }

This code is basically doing the same, but instead of querying for elements on each iteration, it's done once before starting loop.这段代码基本上是做同样的事情,但不是在每次迭代中查询元素,而是在开始循环之前完成一次。 Then loop over the buttons one by one and add click event to each one of them.然后逐个循环按钮并为每个按钮添加点击事件。

You can also use for..of it might be easier to understand.您也可以使用for..of它可能更容易理解。 Here's the code updated to use 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; }); }

Update: The main thing to understand in both code snippets is const text = this.innerHTML .更新:在这两个代码片段中要理解的主要内容是const text = this.innerHTML This line of code is using the this keyword to get the HTML content of each button.这行代码就是使用this关键字来获取每个按钮的 HTML 内容。 this keyword will be pointing to button triggered the event, so based on that you're getting text displayed on that button using innerHTML property and concatenate that to content of h1. this关键字将指向触发事件的按钮,因此基于此,您将使用innerHTML属性在该按钮上显示文本并将其连接到 h1 的内容。 In short, getting text in clicked button and append to h1 content.简而言之,将单击按钮中的文本和 append 获取到 h1 内容。

I have removed console.log(i) as it refers to variable i that is valid only while add the event listener callback only.我已经删除了console.log(i)因为它引用了仅在添加事件侦听器回调时才有效的变量i It'll show an error because when event callback function is called there will be no for loop and i won't be defined.它会显示一个错误,因为当事件回调 function 被调用时,将没有 for 循环并且我不会被定义。

For in the nodelist attach an event listener that calls a function when the button is clicked.节点列表中附加一个事件侦听器,该侦听器在单击按钮时调用 function。 The function updates the h1 with the button text. function 使用按钮文本更新h1

Your code can be improved slightly by caching all the elements up front, and then using those references in the loop (a for/of loop is a little easier to parse) instead.通过预先缓存所有元素,然后在循环中使用这些引用(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>

You could even use event delegation .您甚至可以使用事件委托 It attaches one listener to a parent element which captures events from its child elements as they "bubble up" the DOM.它将一个侦听器附加到父元素,当子元素“冒泡”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>

Additional information附加信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM