Есть ли способ вызвать eventListener более одного раза в javascript? - PullRequest
1 голос
/ 27 мая 2020

Я пытаюсь вызвать прослушиватель событий для всех 4 индикаторов выполнения, но он работает только над первым. Я клонировал div с id = mycontainer, используя для l oop, но eventListener распознает только первый индикатор выполнения, в другом он не работает. Вот мой код

</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>

Ответы [ 2 ]

2 голосов
/ 27 мая 2020

Замените id на класс

id должен быть уникальным для каждого элемента.

Когда вы сделаете document.getElementById, он вернет только первый совпавший элемент.

Таким образом, вы должны использовать class вместо id.

Поскольку document.getElementsByClassName возвращает все совпадающие элементы с className.

Также вы должны привязать прослушиватель событий к document, а затем проверьте элемент.

Поскольку ваши элементы создаются динамически, а addEventListener связывает событие только с элементами, которые присутствуют в DOM.

Как

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>
1 голос
/ 27 мая 2020

Назначьте всем индикаторам выполнения один и тот же класс:

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

Назначьте переменную document.querySelectorAll(".progress-bar") - это выберет все из них и вернет список узлов:

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

L oop через каждый, используя .forEach, и добавьте к нему прослушиватель событий:

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

Результат: каждому индикатору выполнения назначен прослушиватель событий «изменение».

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...