Questions related to clicks on js events

1. The code is as follows

<div>
  <p class="cl">
    <label for="box" class="la">man</label>
    <input type="checkbox" id="box">
  

</div> let cl = document.querySelector(".cl") let bx = document.querySelector("-sharpbox") cl.addEventListener("click", function (e) { window.event ? window.event.cancelBubble = true : e.stopPropagation() console.log(e.target) }, true)

2. The question is as follows:
when I listen for click events in el settings, but it triggers twice when I click label, why twice? I also understand that I wrote to allow capture without bubbling, and the second time is that label automatically triggers

3. what I want is to trigger once, and every click will be checked

cl.addEventListener("click", function (e) {
    console.log(56)
    window.event ? window.event.cancelBubble = true : e.stopPropagation()
    if(e.target !== bx) {
      window.event ? window.event.returnValue = false : e.preventDefault()
      bx.checked == true? bx.checked= false : bx.checked= true
    }
  }, true)

4. so my implementation. What method do you feel like you"ve forgotten? The writing is not elegant. Ask the boss to tell me if there is another better solution

.
Jul.14,2022

when I listen for click events in el settings, but it triggers twice when I click label, why twice? I also understand that I wrote to allow capture without bubbling, and the second time is that label automatically triggers

answer your question first. e.target has identified the trigger element, and the second time is checkbox trigger.

DEMO test , you can compare two examples, one with the for attribute and the other without the for attribute.

what I want is to trigger once, and click on it and check
.

just write html and you don't need js .


  

</div>
Menu