Is html tag distribution a shortcut?

Why, when I click inside the box with the black border, the switch is not executed, but when I click on it, it’s not, but not a checkbox?

var checks = document.querySelectorAll("ul li");

for (var i = 0; i < checks.length; i++) {
  checks[i].addEventListener("click", tog);
};

function tog(e) {
  e.currentTarget.classList.toggle("active");
}
ul li {
  background: #3CF;
  padding: 0.25em 0.5em;
  margin: 0.25em 0;
  display: block;
  cursor: pointer;
  text-indent: 1.5em;
}
ul li.active {
  background: #6EF;
}
label {
  display: block;
  width: 100px;
  border: 1px solid black;
}
<ul>
  <li>
    <label>
      <input type="checkbox">1
    </label>
  </li>
  <li>
    <label>
      <input type="checkbox">2
    </label>
  </li>
  <li>
    <label>
      <input type="checkbox">3
    </label>
  </li>
</ul>
Run codeHide result

Thanks!

+4
source share
1 answer

No. As I explained in my other answer . Because of the bubbles in the tag lable, the lablefunction togis called twice . Therefore, the tag lireceives two identical events one after another, therefore the class is activeadded and removed in the opposite way, which causes this problem.

fiddle .


, , target. fiddle, .

var checks = document.querySelectorAll("ul li");

for (var i = 0; i < checks.length; i++) {
  checks[i].addEventListener("click", tog);
};

var i = 0;
function tog(e) {
        if(e.target.tagName.toLowerCase() == 'label') {
            i++;  //if we remove this then i will never increment
            if(i%2 != 0) {
                i++;  //to bring back to even, so next click should work fine
                return;
            }
        }
  e.currentTarget.classList.toggle("active");
}
ul li {
  background: #3CF;
  padding: 0.25em 0.5em;
  margin: 0.25em 0;
  display: block;
  cursor: pointer;
  text-indent: 1.5em;
}
ul li.active {
  background: #6EF;
}
label {
  display: block;
  width: 100px;
  border: 1px solid black;
}
<ul>
  <li>
    <label>
      <input type="checkbox">1
    </label>
  </li>
  <li>
    <label>
      <input type="checkbox">2
    </label>
  </li>
  <li>
    <label>
      <input type="checkbox">3
    </label>
  </li>
</ul>
Hide result

i, IIFE .

+2

Source: https://habr.com/ru/post/1615425/


All Articles