Friday, April 10, 2020

addEventListener adds click event, click delete button parent node will report error, use onclick event but not. What is this reason?

Guys, I am self-learning Meng new because in the practice encountered bugs also went to find but I don't know why, addEventListener deleted Why does the node to be taken away is not a child of this node.

Can achieve the effect of deletion, but that is, there will be errors reported using the traditional method of registration, there will be no error report, but the best sister, ask the big guys to point it, I really don't know why.


<div class="box">
      <textarea name="" id="" cols="30" rows="10"></textarea>
      <button>published</button>
      <ul></ul>
    </div>
    <script>
      const text = document.querySelector("textarea");
      const btn = document.querySelector("button");
      let ul = document.querySelector("ul");
      btn.addEventListener("click", function (e) {
        if (text.value == "") {
          alert("Empty content cannot be published");
        } else if (text.value.length > 120) {
          alert("Content cannot exceed 120 words");
          text.value = "";
        } else {
          var li = document.createElement("li");
          li.innerHTML = text.value.trim() + ` <a href="javascript:;">Delete</a>`;
          ul.insertBefore(li, ul.children[0]);
          text.value = "";
          var as = document.querySelectorAll("ul a");

          for (var i = 0; i < as.length; i++) {
            // Tradition onclick
            // as[i].onclick = function () {
            //   ul.removeChild(this.parentNode);
            //   console.log(this.parentNode);
            //   console.log(as);
            // };
            // addEventListener Event Listening;
            as[i].addEventListener("click", function () {
              ul.removeChild(this.parentNode);
              console.log(this.parentNode);
              console.log(as);
            });
          }
        }
      });
      document.addEventListener("keyup", function (e) {
        if (e.keyCode == 13 && e.ctrlKey == true) {
          btn.click();
        }
      });
    </script>


solutions


You bind a click event to execute it in btn's click event.

So every time btn, will re-add the event binding.

Comb the process:

Add a li > a, recorded as A;
for loop to bind the event to A;
Add a li > a, recorded as B;
The for loop gives A/B all bind events too.
At this point A has been tied twice,That is, when the callback is triggered twice,The first callback has been deleted,The second callback of course can't find the DOM。

And onclick is an attribute assigned, equal to overwriting the first time, so the callback does not fire repeatedly.

If you want to use addEventListener, you should use event proxies (also called event delegates), bubbling. 

No comments:

Post a Comment