I only want to have the click add one count, not repeated additions to the content

StackOverflow https://stackoverflow.com/questions/22162725

  •  19-10-2022
  •  | 
  •  

문제

In class we are learning JavaScript, and we have to find out how to stop the button click from repeatedly adding the count with .insertbefore I'm stumped as to why it continually inserts the count.

      function clicked() {
            console.log("Clicked!");
            var count = "Node Count: "+countChildren(document.getElementById("content"));
            console.log(count);
      try {
            var span = document.createElement("span");
            span.innerHTML = count;
            document.getElementsByTagName("body")[0].insertBefore(span, document.getElementById("content"));
      } catch(ex) {
            console.log("error "+ex)
           }
      }

올바른 솔루션이 없습니다

다른 팁

You need to check if the node is already added.

 var count = ...
 if ( count !== 0 ) {
      return;
 }

 try {
     ...
 }
 catch(ex) {
     ...
 }

Modify your button HTML like this

<input type ="button" onclick="clicked(); this.onclick=null;"/>

so when once click function is executed, this will stop further clicking actions

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top