简体   繁体   中英

Is there any method to call eventListener for more than one time in javascript?

I am trying to call the eventlistener for all of the 4 progress bar but it is only working on the first one.I had clone the div with id=mycontainer by using for loop but the eventListener will only recognize the first progress bar in other its not working.Here is my code

</head>
  <body >
   <div id="headdiv">
       <div id="mycontainer" style="width: auto;float: left;margin-left: 2%;">
    <input
      id="threshold"
      placeholder="threshold value"
      type="text"
      name="thresholdd"
      style="width: 120px; margin-top: 30px;margin-left: 0%; padding: 10px;" />
    <input
      id="live"
      placeholder="live value"
      type="text"
      name="livee"
      style="width: 120px; margin-bottom: 20px;padding: 10px;"   />

    <div id="progress-container" class="progress-container">
      <div id="progress-bar" class="progress-bar"></div>
    </div>
</div>
</div>
  </body>
  <script>
    const progressBar = window.document.getElementById("progress-bar");
    const progressContainer = window.document.getElementById( "progress-container");
    const threshold = window.document.getElementById("threshold"); 
    let thresholdValue, value;
    threshold.addEventListener("change", e => { thresholdValue = e.target.value;});
    live.addEventListener("change", e => {
      value = e.target.value;
      let percentValue = Math.floor((value / (2 * thresholdValue)) * 100);
      let percentMargin = Math.floor((25 * value) / 100);
      console.log(percentValue, percentMargin);
      if ( value < 100) {
        progressBar.style.height = `calc(${value}% - ${percentMargin}px)`;
      } else if (value => 100) {
        progressBar.style.height = `calc(100% - 25px)`;
      } else {
        progressBar.style.height = `0px`;
      }
      if (percentValue < 50) {
        progressBar.style.backgroundColor = "red";
        progressContainer.style.borderColor = "red";
      } else {
        progressBar.style.backgroundColor = "green";
        progressContainer.style.borderColor = "green";
      }
    });  
          for(var i=0;i<4;i++)
          {
 var headdiv=document.getElementById('headdiv');
var elem = document.querySelector('#mycontainer');
var clone = elem.cloneNode(true);
clone.id = 'mycontainer'+i;
headdiv.appendChild(clone);
}
  </script>
</html>

Change id to class

id should be unique to each element.

When you do document.getElementById it will return only first matched element.

So you have to use class instead of id .

As document.getElementsByClassName returns all matching elements with className.

Also you have to bind eventlistener on document and then check for element.

As your elements are dynamically created, and addEventListener only binds event on elements those are present in DOM.

Like

 const progressBar = window.document.getElementById("progress-bar"); const progressContainer = window.document.getElementById("progress-container"); const threshold = window.document.getElementsByClassName("threshold"); let thresholdValue, value; const live = document.getElementsByClassName("live"); document.addEventListener("change", e => { if (e.target.className.indexOf('threshold') > -1) { thresholdValue = e.target.value; } else if (e.target.className.indexOf('live') > -1) { value = e.target.value; let percentValue = Math.floor((value / (2 * thresholdValue)) * 100); let percentMargin = Math.floor((25 * value) / 100); console.log(percentValue, percentMargin); if (value < 100) { progressBar.style.height = `calc(${value}% - ${percentMargin}px)`; } else if (value => 100) { progressBar.style.height = `calc(100% - 25px)`; } else { progressBar.style.height = `0px`; } if (percentValue < 50) { progressBar.style.backgroundColor = "red"; progressContainer.style.borderColor = "red"; } else { progressBar.style.backgroundColor = "green"; progressContainer.style.borderColor = "green"; } } }); for (var i = 0; i < 4; i++) { var headdiv = document.getElementById('headdiv'); var elem = document.querySelector('#mycontainer'); var clone = elem.cloneNode(true); clone.id = 'mycontainer' + i; headdiv.appendChild(clone); }
 <div id="headdiv"> <div id="mycontainer" style="width: auto;float: left;margin-left: 2%;"> <input class="threshold" placeholder="threshold value" type="text" name="thresholdd" style="width: 120px; margin-top: 30px;margin-left: 0%; padding: 10px;" /> <input class="live" placeholder="live value" type="text" name="livee" style="width: 120px; margin-bottom: 20px;padding: 10px;" /> <div id="progress-container" class="progress-container"> <div id="progress-bar" class="progress-bar"></div> </div> </div> </div>

Give all the progress bars the same class:

<div class="progress-bar"></div>

Assign a variable to document.querySelectorAll(".progress-bar") - this will select all of them and return a Node list:

const bars = document.querySelectorAll(".progress-bar");

Loop through each one using .forEach and add an event listener to it:

bars.forEach(bar => bar.addEventListener("change", functionToRun);

Result: each progress bar has a "change" event listener assigned to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM