0

Why number one code, is a normal child event listener code in js is slower than number 2 code, number two is event delegation in js.

// #1
navLink.forEach(function (item) {
item.addEventListener('click', function (e) {
 e.preventDefault();
 const navId = item.getAttribute('href');
 const navEl = document.querySelector(navId);
 navEl.scrollIntoView({ behavior: 'smooth' });
});
});


// #2
navLinks.addEventListener('click', function (e) {
e.preventDefault();

// matching strategy
if (e.target.classList.contains('nav__link')) {
const navId = e.target.getAttribute('href');
const navEl = document.querySelector(navId);
navEl.scrollIntoView({ behavior: 'smooth' });
 }
});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

0 Answers0