0

I'm wondering why the output is "1, 2, 1" instead of "1"?

document.querySelector('label').addEventListener('click', function() {
  console.log(1)
})
document.querySelector('input').addEventListener('click', function() {
  console.log(2)
})
<label>Click me <input type="text"></label>
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
DangoSky
  • 185
  • 1
  • 2
  • 15
  • You add eventListeners to input and the wrapping label. They BOTH get executed each time you click the label. AND the click on the label triggers the click on the input as it should. What was your expectations? You can use cancelBubble if you do not want this – mplungjan Nov 25 '18 at 06:58
  • But I just Click "Click me", which triggers the listening event on – DangoSky Nov 25 '18 at 07:17
  • And if I change the label to div, the result is "1", why is there such a difference? – DangoSky Nov 25 '18 at 07:18
  • That is the special function of an attached label. Clicking it focuses the attached input. – connexo Nov 25 '18 at 07:25
  • https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label – mplungjan Nov 25 '18 at 07:27
  • The problem has been solved. Thanks for your answers. – DangoSky Nov 25 '18 at 07:54

0 Answers0