JavaScript click event listener on class

后端 未结 5 1060
悲&欢浪女
悲&欢浪女 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:13

    Yow can use querySelectorAll to select all the classes and loop through them to assign the eventListener. The if condition checks if it contains the class name.

    const arrClass = document.querySelectorAll(".className");
    for (let i of arrClass) {
      i.addEventListener("click", (e) => {
        if (e.target.classList.contains("className")) {
            console.log("Perfrom Action")
        }
      })
    }
    

提交回复
热议问题