JavaScript click event listener on class

后端 未结 5 975
悲&欢浪女
悲&欢浪女 2020-11-22 10:19

I\'m currently trying to write some JavaScript to get the attribute of the class that has been clicked. I know that to do this the correct way, I should use an event listene

5条回答
  •  隐瞒了意图╮
    2020-11-22 11:01

    With modern JavaScript it can be done like this:

    const divs = document.querySelectorAll('.a');
    
    divs.forEach(el => el.addEventListener('click', event => {
      console.log(event.target.classList[1]);
    }));
    
    
    
      
      
      Example
      
    
    
      
    1
    2
    11

    1. Gets all elements by class name
    2. Loops over all elements with using forEach
    3. Attach an event listener on each element
    4. Uses event.target to retrieve more information for specific element

提交回复
热议问题