繁体   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