有没有一种方法可以在使用 javascript 循环迭代时为每个 html 元素调用一个函数

Is there a way I can call a function for each html element when iterated using javascript loops

我有 HTML 个元素使用 javascript 循环迭代

html 看起来像这样

<div class="description">Item 1</div>
<div class="description">Item 2</div>
<div class="description">Item 2</div>

Javascript

let allItems =  document.querySelectorAll(".description")
  for (let i = 0; i <= allItems.length; i++) {
      allItems[i].addEventListener("click", toggleSpinner.bind(this));
     }
toggleSpinner = () => {
        alert("I clicked") // here should be, for example, "I clicked Item 1,
                           // Or Item 2 or Item 3 depending on which was clicked
      },

如何在单击每个元素时独立调用函数

你看起来像这样吗?

$(document).ready(function(){

  $('div > *').click(function(){
    alert('hi');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div>
  <p> This is a paragraph </p>
  <section> This is a section </section>
  <span> This is a span </span>
  <article> This is an article </article>

</div>

你也许可以使用这样的东西?

toggleSpinner = (data) => {
  console.log(`You clicked item ${data}`) // here should be, for example, "I clicked Item 1,
  // Or Item 2 or Item 3 depending on which was clicked
}


let allItems =  document.querySelectorAll(".description")
for (let i = 0; i < allItems.length; i++) {
 allItems[i].addEventListener("click", toggleSpinner.bind(this, allItems[i].dataset.item));
}
<div class="description" data-item="1">Item 1</div>
<div class="description" data-item="2">Item 2</div>
<div class="description" data-item="3">Item 3</div>

让 allItems = document.querySelectorAll(".description") 对于(让我= 0;我<=allItems.length;我++){ allItems[i].addEventListener("click", () => {toggleSpinner(allItems[i].innerHTML)}); }

toggleSpinner = 内容 => { 警报(I clicked ${content}) },

类似的东西。在函数中添加一个参数,并在循环中定义要添加的内容作为此内容

document.getElementById("getClickedElement").addEventListener("click", function(event) {
  console.log("Clicked element is:- ", event.target.innerHTML);
});
<div id="getClickedElement">
  <div class="description">Item 1</div>
  <div class="description">Item 2</div>
  <div class="description">Item 3</div>
</div>

注意:- 简单地说,您必须将所有元素包装在父 div 中并用该元素绑定 addEventListener。您将获得目标元素数据。